3
votes

I would like to set a message to specific shipping class in Woocommerce checkout page.

I tried using:

add_action( 'woocommerce_review_order_before_order_total', 'cart_items_shipping_class_message', 20, 1 );
function cart_items_shipping_class_message( $cart ){

    $shipping_class_id = 14; // Your shipping class Id

    // Loop through cart items
    foreach( WC()->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 ){
            var_dump($cart_item['data']->get_shipping_class_id());
            echo "Do poznámky k objednávce napište adresu Zásilkovny nebo ZBoxu, kam chcete objednávku doručit.";
            //break;
        //}
    } 
}

But when I try to var_dump selected shipping class, it always returns me int(0).

I have used something similar to: Cart Message for a Specific Shipping Class in WooCommerce, because It did not work for me.

1
Your code works for me. Try following @LoicTheAztec's suggestion in his answer.Vincenzo Di Gaetano

1 Answers

3
votes

The Cart Message for a Specific Shipping Class in WooCommerce answer still works on last woocommerce version.

Your question code works and display the shipping class Id… So there is something else that is making trouble.

Be sure that a cart item has the required shipping class set for it.

Try following to display a message in checkout based for specific shipping class slug:

add_action( 'woocommerce_review_order_before_order_total', 'checkout_shipping_class_message' );
function checkout_shipping_class_message(){
    // Here your shipping class slugs in the array
    $shipping_classes = array('truck');
    // Here your shipping message
    $message = __("Please add some shipping details in order notes field.", "woocommerce");

    // Loop through cart items
    foreach( WC()->cart->get_cart() as $cart_item ){
        $shipping_class = $cart_item['data']->get_shipping_class();
        
        // echo '<pre>' . print_r($shipping_class, true) . '</pre>'; // Uncomment for testing

        // Check cart items for specific shipping class, displaying a message
        if( in_array($shipping_class, $shipping_classes ) ){
            echo '<tr class="shipping-note">
                <td colspan="2"><strong>'.__("Note", "woocommerce").':</strong> '.$message.'</td>
            </tr>';
            break;
        }
    }
}

Code goes in functions.php file of the active child theme (or active theme). Tested and works.