仅为特定类别重命名 WooCommerce 运输完整标签

Rename WooCommerce shipping full label only for specific categories

我正在尝试重命名特定产品类别的运输规则标签

如果类别 = 雨衣或 T 恤,则运输角色标签 = 自定义标签

否则显示标准标签。


我已经设法让重命名工作,但是当我在代码中指定一个类别时,它只是删除所有标签或抛出错误。

这是我目前的代码,我远不是专家,所以我明白这可能不是正确的方法。

add_filter( 'woocommerce_cart_shipping_method_full_label', 'change_shipping_label', 10, 2 );

function change_shipping_label() {
    HERE define your product categories in the array (Ids, slugs or names)
    $categories = array( 'rain-coats', 't-shirts' );

    $product_id = $cart_item['product_id'];
    $found = false;

     Loop through cart items to find out specific product categories
    foreach( WC()->cart->get_cart() as $cart_item )
        if( has_term( $categories, 'product_cat', $product_id ) ) {
           $found = true;
            $full_label = str_replace( "Current Label", "New Label", $full_label );
            return $full_label;
        }
}

非常感谢任何帮助,我在这些方面还是个新手。

您的代码中存在一些错误和缺失。请尝试以下操作:

add_filter( 'woocommerce_cart_shipping_method_full_label', 'change_shipping_full_label_based_on_product_categories', 10, 2 );
function change_shipping_full_label_based_on_product_categories( $label, $method ) {
    // HERE define your product categories in the array (Ids, slugs or names)
    $categories = array( 'rain-coats', 't-shirts' );

    // Loop through cart items to find out specific product categories
    foreach( WC()->cart->get_cart() as $cart_item ) {
        if( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {
            $label = str_replace( "Current Label", "New Label", $label );
            break;
        }
    }
    return $label;
}

代码进入活动子主题(或活动主题)的 functions.php 文件。它应该有效。