phpwordpresswoocommercecartnotice

Cart Message for a Specific Shipping Class in WooCommerce


I'm trying to add a cart message for a specific shipping class. Adapted from Cart Message for a specific shipping class and a minimal cart total in Woocommerce answer, this is my code attempt:

add_action( 'woocommerce_before_calculate_totals', 'cart_items_shipping_class_message', 20, 1 );
function cart_items_shipping_class_message( $cart ){
    if ( is_admin() && ! defined('DOING_AJAX') )
        return;
    
    $shipping_class = '150';
   
    // Loop through cart items
    foreach( $cart->get_cart() as $cart_item ){
        
        if( $cart_item['data']->get_shipping_class() === $shipping_class ){
        wc_clear_notices();
                
        wc_add_notice( sprintf( 'Beers can only be shipped via <a title="Pallet Shiping" href="/shipping-delivery/#Pallet_Shipping" target="_blank" rel="noopener noreferrer">Pallet Shiping</a>. To reveal much cheaper UPS Shipping Rates, remove Beers from the Cart.'), 'notice' );
        }
    }
}

But it doesn't seem to be working. Any ideas?


Solution

  • In your case it seems that you have defined a shipping class Id in your question code, so you need to use the WC_Product get_shipping_class_id() method instead as follow:

    add_action( 'woocommerce_before_calculate_totals', 'cart_items_shipping_class_message', 20, 1 );
    function cart_items_shipping_class_message( $cart ){
    
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
    
        if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
            return;
    
        $shipping_class_id = '150'; // 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(
                    __('Beers can only be shipped via %s. To reveal much cheaper UPS Shipping Rates, remove Beers from the Cart.', 'woocommerce'),
                    '<a title="Pallet Shipping" href="/shipping-delivery/#Pallet_Shipping" target="_blank" rel="noopener noreferrer">' . __("Pallet Shipping", "woocommerce") . '</a>'
                ), 'notice' );
                break;
            }
        }
    }
    

    Code goes in functions.php file of your active child theme (or active theme). It should work.


    Addition: To display the notice only on cart page, replace the following code:

        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
    

    by this:

        if ( ! is_cart() || ( is_admin() && ! defined( 'DOING_AJAX' ) ) )
            return;