Created
August 24, 2018 21:54
-
-
Save michaelbourne/a2fbebbc839a41c4204524fcd020061e to your computer and use it in GitHub Desktop.
Add a body class when there are items in the Woocommerce cart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@andrewjohnstrong not sure, why you would need that inside your class, but this function has the cart count:
WC()->cart->get_cart_contents_count()