Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting country name from country code in WooCommerce

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?

like image 898
Christian Mayne Avatar asked Aug 27 '14 13:08

Christian Mayne


People also ask

How do I change my country in WooCommerce?

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.

How do I find my billing address in WooCommerce?

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();


2 Answers

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() ] : '';
like image 63
Claudio Sanches Avatar answered Oct 17 '22 22:10

Claudio Sanches


To get the state name from state code you can use.

WC()->countries->states[$order->billing_country][$order->billing_state];
like image 37
Ashish Khatri Avatar answered Oct 17 '22 21:10

Ashish Khatri