Woocommerce 从运输方式 ID 中获取运输区域名称

Woocommerce 从运输方式 ID 中获取运输区域名称

问题描述:

我有一个返回 $shipping_method_id 的函数(例如 flat_rate:3).我想获取此送货方式费率 ID 的区域名称...

I have a function that returns the $shipping_method_id (for example flat_rate:3). I would like to get the Zone name for this Shipping method rate ID…

如何根据Shipping method rate ID获取区域名称?

How to get zone name according to the Shipping method rate ID?

构建一个自定义函数,以这种方式使用非常简单的 SQL 查询:

Building a custom function that will use very simple SQL queries this way:

function get_shipping_zone_from_method_rate_id( $method_rate_id ){
    global $wpdb;

    $data = explode( ':', $method_rate_id );
    $method_id = $data[0];
    $instance_id = $data[1];

    // The first SQL query
    $zone_id = $wpdb->get_col( "
        SELECT wszm.zone_id
        FROM {$wpdb->prefix}woocommerce_shipping_zone_methods as wszm
        WHERE wszm.instance_id = '$instance_id'
        AND wszm.method_id LIKE '$method_id'
    " );
    $zone_id = reset($zone_id); // converting to string

    // 1. Wrong Shipping method rate id
    if( empty($zone_id) )   
    {
        return __("Error! doesn't exist…");
    } 
    // 2. Default WC Zone name 
    elseif( $zone_id == 0 ) 
    {
        return __("All Other countries");
    }
    // 3. Created Zone name  
    else                       
    {
        // The 2nd SQL query
        $zone_name = $wpdb->get_col( "
            SELECT wsz.zone_name
            FROM {$wpdb->prefix}woocommerce_shipping_zones as wsz
            WHERE wsz.zone_id = '$zone_id'
        " );
        return reset($zone_name); // converting to string and returning the value
    }
}

代码位于活动子主题(或主题)的 function.php 文件或任何插件文件中.

经过测试并有效.

使用示例 (输出区域名称):

// Set HERE your shipping method rate id
$rate_id = 'flat_rate:3';
// Get the zone name
$zone_name = get_shipping_zone_from_method_rate_id( $rate_id );

// Output zone name
echo  $zone_name;