Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save michaelbourne/a2fbebbc839a41c4204524fcd020061e to your computer and use it in GitHub Desktop.
Save michaelbourne/a2fbebbc839a41c4204524fcd020061e to your computer and use it in GitHub Desktop.
Add a body class when there are items in the Woocommerce cart
<?php
// Add a body class via the body_class filter in WP
// =============================================================================
add_filter( 'body_class', 'mb_body_class_for_cart_items' );
function mb_body_class_for_cart_items( $classes ) {
if( ! WC()->cart->is_empty() ){
$classes[] = 'cart-has-items';
}
return $classes;
}
// Add a body class via javascript for AJAX enabled sites
// =============================================================================
add_action( 'wp_footer', 'mb_body_class_for_ajax_add_to_cart' );
function mb_body_class_for_ajax_add_to_cart() {
?>
<script type="text/javascript">
(function($){
$('body').on( 'added_to_cart', function(){
if( ! $(this).hasClass('cart-has-items') ){
$(this).addClass('cart-has-items');
}
});
})(jQuery);
</script>
<?php
}
@oxwebdevelopment
Copy link

This would be even better if the class indicated exactly how many items were in the cart too :)

@jnz31
Copy link

jnz31 commented Feb 8, 2022

@andrewjohnstrong not sure, why you would need that inside your class, but this function has the cart count: WC()->cart->get_cart_contents_count()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment