Add class to woocommerce checkout body based on filter [closed]

As @cjbj noted in a comment, this is probably a timing issue. This means that instead of directly adding the code to functions.php you need to wrap it inside a callback function and attach it to a later firing action. WordPress, themes and plugins too, loads and does things in certain order. Thus some code needs to be added with actions to make them properly.

Personally, I usually add body_class filtering, if it depends on some data, on template_redirect (Fires before determining which template to load) action to make sure the code will have all the data it needs to determine how to filter the classes.

// Hook anonymous callback to template_redirect action
add_action(
    'template_redirect',
    function(){
        // Get data
        $cart_items = wcs_cart_contains_renewal();
        // Check for truthy condition
        if ( $cart_items ) {
            // Hook anonymous callback to body_class filter
            add_filter(
                'body_class',
                function( $classes ) {
                    // Add additional class
                    $classes[] = 'renewal-order';
                    return $classes;
                }
            );
        }
    }
);

You can use named callback instead of anonymous ones, if you wish.

Leave a Comment