Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign the user ID to an order created programmatically in Woocommerce 3

I’m using Woocommerce to manage my products on Wordpress, but the user pay through a 3rd party service.

I’m trying to create new order manually, and assign it to the current user.The order is indeed created and logged but the following code only log the item and the time, no details of the user:

  global $woocommerce;

  $address = array(
      'first_name' => $_GET['FirstName'],
      'last_name'  => $_GET['LastName'],
      'company'    => $_GET['CompanyName'],
      'email'      => $_GET['EmailAddress'],
      'phone'      => $_GET['MobilePhoneNumber'],
      'address_1'  => '',
      'address_2'  => '',
      'city'       => '',
      'state'      => '',
      'postcode'   => '',
      'country'    => $_GET['countryCode']
  );

  $order = wc_create_order();

  foreach ($woocommerce->cart->get_cart() as $cart_item_key => $values) {
            $item_id = $order->add_product(
                    $values['data'], $values['quantity'], array(
                'variation' => $values['variation'],
                'totals' => array(
                    'subtotal' => $values['line_subtotal'],
                    'subtotal_tax' => $values['line_subtotal_tax'],
                    'total' => $values['line_total'],
                    'tax' => $values['line_tax'],
                    'tax_data' => $values['line_tax_data'] // Since 2.2
                )
                    )
            );
        }
  $order->set_address( $address, 'billing' );
  //
  $order->calculate_totals();
  $order->update_status("Completed", 'Imported order', TRUE);  
$order->save();

The admin can see what was ordered (under woocommerce->orders) but not by whom, and the user can’t see his orders at all.

I've uploaded the website to a temporary domain so you guys can see: https://360transformations.000webhostapp.com/?page_id=446

like image 557
TheProphet Avatar asked Jan 28 '23 02:01

TheProphet


2 Answers

Assign the user ID to an order, Use below options

Option 1:

$userid = get_current_user_id();
$order = wc_create_order(array('customer_id'=>$userid));

Option 2:

add below code after wc_create_order() function

$userid = get_current_user_id();
update_post_meta($order->id, '_customer_user', $userid);
like image 155
mithun raval Avatar answered Jan 30 '23 15:01

mithun raval


You will have to add the customer ID using set_customer_id() CRUD setter method:

$order->set_customer_id( $user_id );

Where $user_id should be the current user Id or a defined user ID… This Id will be 0 for guest users. To get the current user ID you will use:

$user_id = get_current_user_id();
$order->set_customer_id( $user_id );
like image 26
LoicTheAztec Avatar answered Jan 30 '23 15:01

LoicTheAztec