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;
}
}
}