Mr Toad
Mr Toad

Reputation: 256

Add a custom body class when basket has items in Woocommerce

I am trying to make some styling adjustments when my woocommerce cart had basket items.

When items are added, a 'pay now with paypal' button appears but it's default positioning needs fixed. Unfortunately I cannot see any classes that appear when this button appears.

Does anyone know how to add a class to the body when the cart total is no longer zero?

Any help would be appreciated.

Upvotes: 2

Views: 1630

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 254019

This can be done with the following two hooked functions:

  • The first one will add 'has_items' class to body when cart is not empty
  • The second one will add 'has_items' class to body (if not set yet) on Ajax add to cart event.

The code:

add_filter( 'body_class', 'add_body_class_for_cart_items' );
function add_body_class_for_cart_items( $classes ) {
    if( ! WC()->cart->is_empty() )
        $classes[] = 'has_items';

    return $classes;
}

add_action( 'wp_footer', 'add_body_class_for_ajax_add_to_cart' );
function add_body_class_for_ajax_add_to_cart() {
    ?>
        <script type="text/javascript">
            (function($){
                $('body').on( 'added_to_cart', function(){
                    if( ! $(this).hasClass('has_items') )
                        $(this).addClass('has_items');
                        console.log('added_to_cart');
                });
            })(jQuery);
        </script>
    <?php
}

Code goes in function.php file of your active child theme (or theme).

Tested and works.

Upvotes: 3

Related Questions