3

在提出这个问题之前,我知道可能还有其他方法可以实现目标,但我试图了解 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 中显示“统一运费:”的部分,具体取决于运费的成本。任何帮助将非常感激。

4

1 回答 1

3

对于特定运费 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 文件中。它应该有效。

清除运输缓存

  • 您需要清空购物车,以清除缓存的运输数据
  • 或者在运输设置中,您可以禁用/保存任何运输方式,然后启用返回/保存。
于 2020-10-09T22:55:14.213 回答