split order after checkout depending on products vendors (WCFM Marketplace)

by Forward Web   Last Updated October 19, 2019 17:08 PM - source

I need to split order before thank you page view depending on products vendors for example If the order contains 5 products from different vendors - 2 products from X vendor - 2 products from Z vendor - 1 product from S vendor so I need to generate 3 different orders from the original order data and store the generated orders instead of the original order I'm using WCFM marketplace plugin, and I found a premium plugin that doing this but for another multi-vendor plugin

Here is what I done in code, but I get Internal Server Error

add_action( 'woocommerce_checkout_create_order', 'HF_before_checkout_create_order', 20, 2 ); 
function HF_before_checkout_create_order( $order, $data ){
  global $wpdb;
  global $WCFM;
  global $woocommerce;

  $vendors = array();

  foreach( $order->get_items() as $key => $item ) {
    $product_id = $item['product_id'];
    $vendor = $WCFM->wcfm_vendor_support->wcfm_get_vendor_id_from_product( $product_id );
    if( $vendor ) {
      $vendors[] = $vendor;
      // wc_delete_order_item( $key );
    }

    if( count($vendors) ) :

      foreach( $vendors as $vendor_order ) :

          $order_seller = new WC_Order();

          foreach( $data['line_items'] as $line_item ) {
              $args = $line_item['args'];
              $product = wc_get_product( isset($args['variation_id']) && $args['variation_id'] > 0 ? $$args['variation_id'] : $args['product_id'] );
              $product_vendor = $WCFM->wcfm_vendor_support->wcfm_get_vendor_id_from_product( $product->ID );
              if( $product_vendor == $vendor_order ) :
                $order_seller->add_product( $product, $line_item['quantity'], $line_item['args'] );
              endif;
          }

        $order_seller->set_address( $order->get_address( 'billing' ), 'billing' );
        $order_seller->set_address( $order->get_address( 'shipping' ), 'shipping' );

        $order_seller->calculate_taxes();
        $order_seller->calculate_totals();
        $order_seller->save();

      endforeach;

    endif;
  }

  $order->update_status(
    'cancelled',
    __( 'This order has been splitted to separate orders' )
  );
  $history = $order->addStatusHistoryComment('Order marked as cancelled.', false);
  $history->setIsCustomerNotified(false);
  $order->save();

}
Tags : woocommerce


Related Questions


How can add and preview product Frontend

Updated March 26, 2015 12:02 PM


How to add "Reply-to" in Woocommerce

Updated April 04, 2015 15:03 PM


WooCommerce epdq gateway Change order status

Updated April 06, 2015 19:03 PM