Woocommerce get shipping zone name from the shippi

2019-08-01 10:49发布

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…

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

1条回答
时光不老,我们不散
2楼-- · 2019-08-01 11:09

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
    }
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works.


Usage example (output the zone name):

// 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;
查看更多
登录 后发表回答