WooCommerce 购物车和结帐中用于运输(标签)方法的额外 HTML

Extra HTML for shipping (label) methods in WooCommerce cart and checkout

我正在尝试将预计到达时间添加到我的送货方式标签上。但是,我希望到达时间在标签中有一些奖励 HTML。 (使它们更小和不同的字体粗细)。

这是一个简单的例子:

function add_estimated_arrival_times($rates, $package){
    
    $groundStuff = $timeReturnedFromAPI; //collect a bunch of cart information, post to the UPS API, return estimated arrival time to $timeReturnedFromAPI
    $ground_rate_id = 'ups:6:09'; //UPS ground rate ID
    
    // Loop through available shipping rates, add arrival time if rate is UPS ground
    foreach ( $rates as $rate_key => $rate ) {
        if( $ground_rate_id === $rate_key ) {
            $rates[$rate_key]->label .= ' <span style="font-size: 12px; font-weight: normal;">(' . $groundStuff . ')</span>'; //<---- problem: HTML is not added
            break;
        }
    }

    return $rates;
}
add_filter( 'woocommerce_package_rates','add_estimated_arrival_times', 50, 2 );

上面的代码成功地将纯文本添加到运输方式标签,但是 HTML 消失了。

对此有什么好的解决方法?

您使用的钩子只允许您编辑标签的文本:

function filter_woocommerce_package_rates( $rates, $package ){    
    // Loop through available shipping rates
    foreach ( $rates as $rate_key => $rate ) {
        $rates[$rate_key]->label = __( 'My label', 'woocommerce' );
    }

    return $rates;
}
add_filter( 'woocommerce_package_rates','filter_woocommerce_package_rates', 10, 2 );

也可以通过 woocommerce_cart_shipping_method_full_label 挂钩进行调整:

function filter_woocommerce_cart_shipping_method_full_label( $label, $method ) {
    // Target a specific method ID
    if ( $method->id == 'local_pickup:1' ) {
        // Overwrite
        $label = __( 'My new label', 'woocommerce' );
    } elseif ( $method->id == 'free_shipping:2' ) {
        // Append
        $label .= __( ' - Extra text label', 'woocommerce' );
    }

    return $label; 
}
add_filter( 'woocommerce_cart_shipping_method_full_label', 'filter_woocommerce_cart_shipping_method_full_label', 10, 2 );

但是您的问题是在标签后添加一些内容,这可以通过 woocommerce_after_shipping_rate 挂钩来完成:

function action_woocommerce_after_shipping_rate( $method, $index ) {
    // Target a specific method ID
    if ( $method->id == 'local_pickup:1' ) {
        echo '<p>test</p>';
    } else {
        $groundStuff = 'some value';
        
        echo '<span style="font-size: 12px; font-weight: normal;">(' . $groundStuff . ')</span>';
    }
}
add_action( 'woocommerce_after_shipping_rate', 'action_woocommerce_after_shipping_rate', 10, 2 );

通过在第 40 行覆盖 /cart/cart-shipping.php @version 3.6.0 - 这个模板可以通过复制到 yourtheme/woocommerce/cart/cart-shipping.php

来覆盖