How can I get customer details from an order in WooCommerce?

Alfonso Pérez picture Alfonso Pérez · Apr 3, 2014 · Viewed 133.2k times · Source

I have a function that does this:

$order = new WC_Order($order_id);
$customer = new WC_Customer($order_id);

How can I get customer details from this?

I have tried everything in the documentation, but somehow, just some details are present, but the rest aren't. For example.

$data['Address'] = $customer->get_address() . ' ' . $customer->get_address_2();
$data['ZipCode'] = $customer->get_postcode();

Is empty.

Doing

var_dump($customer)

Produces:

object(WC_Customer)#654 (2) { ["_data":protected]=> array(14) { ["country"]=> string(2) "IT" >["state"]=> string(0) "" ["postcode"]=> string(0) "" ["city"]=> string(0) "" ["address"]=> >string(0) "" ["address_2"]=> string(0) "" ["shipping_country"]=> string(2) "IT" ["shipping_state"]=> string(2) "BG" ["shipping_postcode"]=> string(0) "" ["shipping_city"]=> >string(0) "" ["shipping_address"]=> string(0) "" ["shipping_address_2"]=> string(0) "" ["is_vat_exempt"]=> bool(false) ["calculated_shipping"]=> bool(false) } ? ["_changed":"WC_Customer":private]=> bool(false) }

As you can see, the city is present, but the rest are empty. I have checked in wp_usermeta database table and in the administrator panel of the customer and all the data is there.

Answer

Ratnakar - StoreApps picture Ratnakar - StoreApps · Apr 3, 2014

If you want customer's details that customer had entered while ordering, then you can use the following code:

$order = new WC_Order($order_id);
$billing_address = $order->get_billing_address();
$billing_address_html = $order->get_formatted_billing_address();

// For printing or displaying on the web page
$shipping_address = $order->get_shipping_address();
$shipping_address_html = $order->get_formatted_shipping_address(); // For printing or displaying on web page

Apart from this, $customer = new WC_Customer( $order_id ); can not get you customer details.

First of all, new WC_Customer() doesn't take any arguments.

Secondly, WC_Customer will get customer's details only when the user is logged in and he/she is not on the admin side. Instead he/she should be on website's front-end like the 'My Account', 'Shop', 'Cart', or 'Checkout' page.