WooCommerce defines countries as follows (edited for brevity):
class WC_Countries {
public $countries;
public function __construct() {
global $woocommerce, $states;
$this->countries = apply_filters( 'woocommerce_countries', array(
'AF' => __( 'Afghanistan', 'woocommerce' ),
'AX' => __( 'Åland Islands', 'woocommerce' ),
'AL' => __( 'Albania', 'woocommerce' ),
'DZ' => __( 'Algeria', 'woocommerce' ),
// […]
));
}
}
When an order is placed, the country code is written to the WordPress wp_postmeta
table and can be extracted anywhere an order id can be accessed using the get_post_meta()
function:
get_post_meta( $order->id, '_shipping_country', true ),
Since we are simply retrieving two characters from the database, the question is how to translate the shipping country code (e.g. AF
) to the country name specified in the WC_Countries
class?
Setting the WooCommerce Base Location Select your preferred location from a drop-down. You need to set up Address Line 1 & 2, City, State, Country and Postcode. Set up the address details of your store. Next, in the General Options section, you can set your Selling Location.
You can fetch billing address by using WC_Order object and get_billing_address() from order id. Use the following code to fetch billing address from order ID. $order = new WC_Order( $order_id ); $billing_address=$order->get_billing_address();
You can access the WC_Countries
class with WC()->countries
. So to get the country name from an order, you must use:
WC()->countries->countries[ $order->shipping_country ];
On WooCommerce 3.0+ you should use:
WC()->countries->countries[ $order->get_shipping_country() ];
If you like to get the state, you need before check if exist, since WooCommerce doesn't include all states, so here what do you need:
$states = WC()->countries->get_states( $order->get_shipping_country() );
$state = ! empty( $states[ $order->get_shipping_state() ] ) ? $states[ $order->get_shipping_state() ] : '';
To get the state name from state code you can use.
WC()->countries->states[$order->billing_country][$order->billing_state];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With