Check if cart is NOT empty in Woocommerce 3

user5483053 picture user5483053 · Jun 1, 2018 · Viewed 13.5k times · Source

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   }
    } ?>

Answer

Justin R. picture Justin R. · Jun 1, 2018
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.