从 WooCommerce 中的国家/地区代码获取国家/地区名称 [英] Getting country name from country code in WooCommerce

查看:82
本文介绍了从 WooCommerce 中的国家/地区代码获取国家/地区名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Wordpress 中的 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' ),

        ));
    }
}

下订单时,国家/地区代码将写入 Wordpress wp_postmeta 表,并且可以在任何可以使用 get_post_meta() 函数访问订单 ID 的地方提取:

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 ),

问题是,如果只是从数据库中提取两个字符,那么如何将运输国家/地区代码(例如 AF)转换为国家类中给出的国家/地区名称?

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?

推荐答案

您可以使用 WC()->countries 访问 WC_Countries 类.因此,要从订单中获取国家/地区名称,您必须使用:

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 ];

在 WooCommerce 3.0+ 上,您应该使用:

On WooCommerce 3.0+ you should use:

WC()->countries->countries[ $order->get_shipping_country() ];

如果你想获取状态,你需要先检查是否存在,因为 WooCommerce 不包括所有状态,所以这里你需要什么:

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

这篇关于从 WooCommerce 中的国家/地区代码获取国家/地区名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆