( Woocommerce) How to get the user belonging to an order? [closed]

From the __get() method in the WC_Order class you can see that the user_id property is taken from/stored as _customer_user post meta for the order in question.

/**
 * __get function.
 *
 * @access public
 * @param mixed $key
 * @return mixed
 */
public function __get( $key ) {
    // Get values or default if not set
    if ( 'completed_date' == $key ) {
        $value = ( $value = get_post_meta( $this->id, '_completed_date', true ) ) ? $value : $this->modified_date;
    } elseif ( 'user_id' == $key ) {
        $value = ( $value = get_post_meta( $this->id, '_customer_user', true ) ) ? absint( $value ) : '';
    } else {
        $value = get_post_meta( $this->id, '_' . $key, true );
    }

    return $value;
}

So in your code you can grab the user id like so:

$order = new WC_Order( $order_id );
$user_id = $order->user_id;

I presume you’re not going to allow guest checkout, but you might want some kind of fallback in case there isn’t a user id.

Update for WooCommerce 3.0

Disregard all of the above. As pointed out in the comments there are direct methods for getting this information. In fact, almost all “magic methods” have been removed and directly accessing object properties will throw PHP warnings.

$order = wc_get_order( $order_id );
$user = $order->get_user();
$user_id = $order->get_user_id();

Leave a Comment