Search code examples
phpwordpresswoocommerceproductcart

Add shipping class to body class on WooCommerce checkout page


I wish to have added the shipping classes as a body class on the checkout page.

It would be best if all active shipping classes is added, but otherwise add a specific class if a certain shipping class is present in the cart.

Can anyone help me with this.. all other guides I can find only relates to remove rates/shipping options, so really hope for some help here.


Solution

  • The following will add the product(s) (cart item(s)) shipping class(es) as additional body class(es) tag(s) on checkout page:

    add_filter( 'body_class', 'add_shipping_classes_to_body_class' );
    function add_shipping_classes_to_body_class( $classes ) {
        // Only on checkout page
        if( is_checkout() && ! is_wc_endpoint_url() ) {
            // Loop through cart items
            foreach ( WC()->cart->get_cart() as $item ) {
                // If a shipping class is set for the product, we add it to body classes
                if ( $shipping_class = $item['data']->get_shipping_class() )
                    $classes[] = $shipping_class;
            }
        }
        return $classes;
    }
    

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