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

Issue

There is a function that does this:

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

How do I get customer details from here?

I have tried everything in the docs, but somehow only some details are shown and the rest are not. For example,

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

Empty.

doing

var_dump($customer)
 

Produce:

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) “Italy”
[“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 exists, but the rest is empty. I checked in the wp_usermeta database table and the customer’s admin panel and all the data is there.

Solution

Having tried $customer = new WC_Customer(); and global $woocommerce; $customer = $woocommerce->customer; I was still getting empty address data even when I logged in as a non-admin user.

My solution was as follows:

function mwe_get_formatted_shipping_name_and_address($user_id) {

    $address = '';
    $address .= get_user_meta( $user_id, 'shipping_first_name', true );
    $address .= ' ';
    $address .= get_user_meta( $user_id, 'shipping_last_name', true );
    $address .= "\n";
    $address .= get_user_meta( $user_id, 'shipping_company', true );
    $address .= "\n";
    $address .= get_user_meta( $user_id, 'shipping_address_1', true );
    $address .= "\n";
    $address .= get_user_meta( $user_id, 'shipping_address_2', true );
    $address .= "\n";
    $address .= get_user_meta( $user_id, 'shipping_city', true );
    $address .= "\n";
    $address .= get_user_meta( $user_id, 'shipping_state', true );
    $address .= "\n";
    $address .= get_user_meta( $user_id, 'shipping_postcode', true );
    $address .= "\n";
    $address .= get_user_meta( $user_id, 'shipping_country', true );

    return $address;
}

…and this code works regardless of whether you are logged in as admin or not.

Answered By – ban-geoengineering

Answer Checked By – Terry (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published