Add a CSS class to an item when Woocommerce cart is empty

一笑奈何 提交于 2019-12-12 10:00:55

问题


I am trying to hide my cart when it is empty, so I decided to add a CSS class to the cart HTML item when the cart is empty, here is my current code:

 function x_woocommerce_navbar_menu_item( $items, $args ) {
      if (WC()->cart->cart_contents_count == 0 ) {
       echo '<script type="text/javascript">
                    $(document).ready(function() {
                        $("#header_cart").addClass("zero"); 
                    });
               </script>';
      }

I am adding this to my functionts.php file

Am I missing anything?


回答1:


It will be good if you add the class to body to make the hierarchy in CSS. Use the following code in functions.php :

    function tristup_body_classes( $classes )
    {

        global $woocommerce;
        if( is_cart() && WC()->cart->cart_contents_count == 0){
            $classes[]='empty-cart';
        }
        return $classes;
    }
    add_filter( 'body_class', 'tristup_body_classes' );

This code will add a class "empty-cart" to body.
Hope this will solve your problem.




回答2:


I am posting here a solution which bases on Tristup answer, as his answer is not 100% correct which observed Yahya Hussein.

add_filter( 'body_class','shoppingCartNotEmpty' );
function shoppingCartNotEmpty( $classes ) {
    $classes[] = WC()->cart->get_cart_contents_count() ? 'shopping-cart-not-empty' 
                                                       : 'shopping-cart-empty';
    return $classes;
}

When the shopping cart is empty then the CSS class shopping-cart-empty is created, otherwise shopping-cart-not-empty is available.




回答3:


Please put this code in functions.php file.

function cart_empty_add_class() {
    global $woocommerce;
    if ( empty($woocommerce->cart->cart_contents) ) {
        echo '<script type="text/javascript">
                    $(document).ready(function() {
                        $("#header_cart").addClass("zero"); 
                    });
               </script>';
exit;
    }
}
add_action( 'wp_head', 'cart_empty_add_class' );


来源:https://stackoverflow.com/questions/45116017/add-a-css-class-to-an-item-when-woocommerce-cart-is-empty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!