skip to Main Content

Im creating a WooCommerce order programmatically trough a form and I link the order trough the user id:

$order->set_customer_id( $user_id );

I retrieve the customer information via mail instead of ID:

 $user = get_user_by( 'email', $email );

Is it possible to link the order to an existing customer via the existing email instead of the user id? Something like this:

$order->set_customer_id( $email );

Is this possible?

2

Answers


  1. Function get_user_by() returns WP_User object, so you only need to take the ID from the object and substitute it into the function set_customer_id() from $order:

    // $user - it is WP_User object
    $user = get_user_by( 'email', $email );
    $order->set_customer_id( $user->ID );
    
    Login or Signup to reply.
  2. Why would you need to link the order to the customer email when you have his userId? That gives you access to the user object real quick and from there you can access whatever you want. For example $user->user_email would give you his email

    $user = new WP_User($user_id);
    $user_email = $user->user_email;
    

    Another option is that you retrieve those info from the Woocommerce default billing fields, which you should fill (even when creating it programmatically) and you can access those with:

    $order = new WC_Order($id);
    $order->get_billing_email();
    

    Least but not last, save it in any postmeta field of your choice:

    update_post_meta($order_id, 'my_email_custom_field', $email);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search