Woocommerce get shipping zone name from the shipping method id

早过忘川 提交于 2020-01-05 04:17:11

问题


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:


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;


来源:https://stackoverflow.com/questions/47423109/woocommerce-get-shipping-zone-name-from-the-shipping-method-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!