[英]Woocommerce Change shipping method title on checkout based on shipping class selected
[英]Change WooCommerce shipping method full label based on product shipping class
我想在 WooCommerce 的购物车页面上添加自定义消息。该消息应根据分配给产品的运费 class 在woocommerce_cart_shipping_method_full_label
挂钩中显示。
我已经有了执行此操作的代码,但是当我将它分配给该挂钩时它不起作用,只有当我将它分配给woocommerce_before_calculate_totals
挂钩时它才起作用。
当我想将它添加到woocommerce_cart_shipping_method_full_label
挂钩时,我收到消息:
致命错误:未捕获错误:调用成员 function get_cart()
有人可以告诉我我做错了什么吗? 我正在使用带有子主题的店面模板。
基于WooCommerce 答案代码中特定运输 Class 的购物车消息,这是我在函数中使用的代码。php:
add_action( 'woocommerce_cart_shipping_method_full_label', 'cart_items_shipping_class_message', 20, 1 );
function cart_items_shipping_class_message( $cart ){
if ( ! is_cart() || ( is_admin() && ! defined( 'DOING_AJAX' ) ) )
return;
if ( did_action( 'woocommerce_cart_shipping_method_full_label' ) >= 2 )
return;
$shipping_class_id = '28'; // Your shipping class Id
// Loop through cart items
foreach( $cart->get_cart() as $cart_item ) {
// Check cart items for specific shipping class, displaying a notice
if( $cart_item['data']->get_shipping_class_id() == $shipping_class_id ){
wc_clear_notices();
wc_add_notice( sprintf( __('My custom message.', 'woocommerce'), '' . __("Pallet Shipping", "woocommerce") . ''), 'notice' );
break;
}
}
}
将为一个钩子编写的代码映射到另一个钩子有时需要进行一些调整,具体取决于原始钩子和新映射的钩子:
$cart
未传递给回调 function,因此您收到错误消息wc_clear_notices()
和wc_add_notice()
不适用,因为您希望使用的挂钩是更改$label
if ( did_action( 'woocommerce_cart_shipping_method_full_label' ) >= 2 )
不存在所以你得到:
function filter_woocommerce_cart_shipping_method_full_label( $label, $method ) {
// Your shipping class Id
$shipping_class_id = 28;
// WC Cart
if ( WC()->cart ) {
// Get cart
$cart = WC()->cart;
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item ) {
// Check cart items for specific shipping class
if ( $cart_item['data']->get_shipping_class_id() == $shipping_class_id ) {
$label = __( 'My custom message', 'woocommerce' );
break;
}
}
}
return $label;
}
add_filter( 'woocommerce_cart_shipping_method_full_label', 'filter_woocommerce_cart_shipping_method_full_label', 10, 2 );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.