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

删除回忆录丶 提交于 2019-12-06 06:39:22

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.

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 class shopping-cart-empty is created, otherwise shopping-cart-not-empty is available.

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