Ad

How To Get Custom Fields Values From WooCommerce Orders

I have checked similar questions but couldn't resolve the problem.

This is my code so far:

// Add VAT and SSN fields in billing address display
add_filter( 'woocommerce_order_formatted_billing_address', 'custom_add_vergi_dairesi_vergi_no_formatted_billing_address', 10, 2 );
function custom_add_vergi_dairesi_vergi_no_formatted_billing_address( $fields, $order ) {
    $fields['vergi_dairesi'] = $order->billing_vergi_dairesi;
    $fields['vergi_no'] = $order->billing_vergi_no;

    return $fields;
}

It is giving me this error: "billing_vergi_dairesi was called incorrectly. Order properties should not be accessed directly".

So I replaced $order->billing_vergi_dairesi; and $order->billing_vergi_no; with $order->get_billing_vergi_dairesi(); and $order->get_billing_vergi_no(); Then I got: "uncaught Error: Call to undefined method".

What I am doing wrong?

Ad

Answer

Since WooCommerce 3, you need to use the WC_Data method get_meta() with the correct meta key(s) to get custom fields values from the WC_Order Object like:

// Add VAT and SSN fields in billing address display
add_filter( 'woocommerce_order_formatted_billing_address', 'custom_add_vergi_dairesi_vergi_no_formatted_billing_address', 10, 2 );
function custom_add_vergi_dairesi_vergi_no_formatted_billing_address( $fields, $order ) {
    $fields['vergi_dairesi'] = $order->get_meta('billing_vergi_dairesi');
    $fields['vergi_no']      = $order->get_meta('billing_vergi_no');

    return $fields;
}

Or may be starting with an underscore instead like:

// Add VAT and SSN fields in billing address display
add_filter( 'woocommerce_order_formatted_billing_address', 'custom_add_vergi_dairesi_vergi_no_formatted_billing_address', 10, 2 );
function custom_add_vergi_dairesi_vergi_no_formatted_billing_address( $fields, $order ) {
    $fields['vergi_dairesi'] = $order->get_meta('_billing_vergi_dairesi');
    $fields['vergi_no']      = $order->get_meta('_billing_vergi_no');

    return $fields;
}

It should works.

Check in wp_postmeta table that billing_vergi_dairesi and billing_vergi_no are the correct meta keys.

See: How to get WooCommerce order details

Ad
source: stackoverflow.com
Ad