Check if cart is NOT empty in Woocommerce 3

13,081

Solution 1

add_action( 'wp_footer', 'vazio' );
  function vazio() {
     if (sizeof( WC()->cart->get_cart() ) > 0 ) { 
       // do something
     }
   }

This will check to see if there are items in the cart. You can add an else statement or check for equivalence as needed.

Solution 2

In new woocommerce 2.1+ : WC()->cart->cart_contents_count to check cart content count

add_action("template_redirect", 'redirection_function');
function redirection_function(){
    global $woocommerce;
    if( is_cart() && WC()->cart->cart_contents_count == 0){
        wp_safe_redirect( get_permalink( woocommerce_get_page_id( 'shop' ) ) );
    }
}

To check the cart content you can also use this code:

global $woocommerce;
if ( $woocommerce->cart->cart_contents_count != 0 ) {
    // cart has content
} else {
   // cart is empty
}
Share:
13,081
Admin
Author by

Admin

Updated on June 15, 2022

Comments

  • Admin
    Admin almost 2 years

    I can' figure this out, how to check if cart is empty. What am I doing wrong?

    My code:

    add_action( 'wp_footer', 'redirecionar' );
    function redirecionar(){
        global $woocommerce;
        if ( is_page('carrinho-de-compras') and !sizeof($woocommerce->cart->cart_contents) ) {
           // do something
        }
    }    
    

    OR

    add_action( 'wp_footer', 'vazio' );
        function vazio() {
            if ( ! WC()->cart->get_cart_contents_count() == 0 ) { 
               // do something
            }
    }
    

    Solved

    <?php add_action( 'wp_footer', 'vazio' );
        function vazio() {
            if ( ! WC()->cart->is_empty() ) { ?>
            <div style="width: 20%;" class="footer-section <?php echo esc_html($woo);?>">
                <a href="<?php echo 'https://my_web_page.pt/finalizar-compra';?>" title="Finalizar Compra"><i class="fa fa-credit-card"></i></a>
            </div>
        <?php   }
        } ?>
    
  • gidiwe2427
    gidiwe2427 over 2 years
    This will not work if using page cache. (cart content will be updated in fragment via ajax)