'Change WooCommerce shipping method full label based on product shipping class
I want to add a custom message on the cart page in WooCommerce. The message should appear depending on the shipping class assigned to the product, in the woocommerce_cart_shipping_method_full_label hook.
I already have code that does it, but it doesn't work when I assign it to that hook, it only works if I assign it to the woocommerce_before_calculate_totals hook.
When I want to add it to the woocommerce_cart_shipping_method_full_label hook, I get the message:
Fatal error: Uncaught Error: Call to a member function get_cart()
Could someone advise me on what I'm doing wrong? I am using the storefront template with a child theme.
Based on Cart Message for a Specific Shipping Class in WooCommerce answer code, this is the code I'm using in the functions.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;
}
}
}
Solution 1:[1]
Mapping code written for one hook to another hook sometimes takes some tweaking, depending on the original hook and the newly mapped hook:
- For example,
$cartis not passed to the callback function, and hence the error message you get wc_clear_notices()andwc_add_notice()are not applicable, as the hook you wish to use is to change the$labelif ( did_action( 'woocommerce_cart_shipping_method_full_label' ) >= 2 )does not exist
So you get:
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 );
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
