根据其在WooCommerce中的成本更改运输方式标签名称

问题描述

在提出这个问题之前,我知道可能还有其他方法可以实现该目标,但是我试图了解Woocommerce的工作原理如何更好,所以情况是我有一个插件可以根据需要更改运输成本在购物车中的商品上,但我想根据费用更改运费的名称

根据我在HTML中找到的内容,当前的送货方式结构如下:

<td data-title="Shipping">
<ul id="shipping_method" class="shipping__list woocommerce-shipping-methods">
    <li class="shipping__list_item">
        <input type="hidden" name="shipping_method[0]" data-index="0" id="shipping_method_0_flat_rate24" value="flat_rate:24" class="shipping_method" /><label class="shipping__list_label" for="shipping_method_0_flat_rate24">Flat Rate Shipping Fee: <span class="woocommerce-Price-amount amount"><bdi><span class="woocommerce-Price-currencySymbol">&#36;</span>10.00</bdi></span></label>                                
    </li>
</ul>

我正在尝试为我的wordpress主题的functions.PHP文件创建一个函数,我在google上查找了一些代码,发现了一个涉及“ $ available_shipping_methods”的类似函数,但我不太确定如何使用它变量,所以我当前拥有的是这个

add_filter('woocommerce_package_rates','wc_shipping_rate_rename',100,2)

function wc_shipping_rate_rename($rates,$package){
    //Checking if the shipping rate exists
    if ( isset( $rates['flat_rate:24'] ) ) {
        //Getting the rate
        $ship_cost = $rates['flat_rate:24']->cost;
        if ( $ship_cost == 10) {
            $rates['flat_rate:24'] -> 'Subsidized shipping fee:';
        }
        if ( $ship_cost == 100) {
            $rates['flat_rate:24'] -> 'Flat rate shipping fee:';
        }
    }
    return $rates;
}

目标是根据运输费用更改HTML中标有“统一费率运输费用:”的部分。任何帮助将不胜感激。

解决方法

对于特定的运费ID,要根据其费用用途更改显示的运费标签:

add_filter('woocommerce_package_rates','custom_shipping_rate_label_based_on_cost',100,2)
function custom_shipping_rate_label_based_on_cost( $rates,$package ){
    // Here your targeted shipping rate Id
    $targeted_rate_id = 'flat_rate:24';
    
    // Loop through available shipping rates
    foreach ( $rates as $rate_key => $rate ) {
        // Targetting specific rate Id
        if( $targeted_rate_id === $rate_key ) {
            $rate_cost = $rate->cost;
            
            if ( $rate_cost < 100 ) {
                $rate_label = __('Subsidized shipping fee');
            } 
            elseif ( $rate_cost >= 100 ) {
                $rate_label = __('Flat rate shipping fee');
            }
            
            if ( isset($rate_label) ) {
                $rates[$rate_key]->label = $rate_label;
            }
        }
    }
    return $rates;
}

代码进入活动子主题(或活动主题)的functions.php文件中。应该可以。

清除运输缓存

  • 您将需要清空购物车,以清除缓存的运输数据
  • 或者在运输设置中,您可以禁用/保存任何运输方式,然后启用回退/保存。