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

Categories

0 votes
998 views
in Technique[技术] by (71.8m points)

php - Getting country name from country code in WooCommerce

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

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

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...