Search code examples
phpwordpresswoocommerce

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


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.


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.