Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

WooCommerce in Wordpress defines the countries class as follows (edited fro 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 ),

The question is, as weare simply pulling two characters from the DB, how can the Shipping country code (eg AF) be translated to the Country Name given in the Countries class?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
963 views
Welcome To Ask or Share your Answers For Others

1 Answer

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() ] : '';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...