4

我无法弄清楚,如何检查购物车是否为空。我究竟做错了什么?

我的代码:

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

或者

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

解决了

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

3 回答 3

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

这将检查购物车中是否有物品。您可以根据需要添加 else 语句或检查等效性。

于 2018-05-31T22:43:27.527 回答
1

在新的 woocommerce 2.1+ 中:WC()->cart->cart_contents_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' ) ) );
    }
}

要检查购物车内容,您还可以使用以下代码:

global $woocommerce;
if ( $woocommerce->cart->cart_contents_count != 0 ) {
    // cart has content
} else {
   // cart is empty
}
于 2018-06-28T07:29:03.750 回答
0

对于 ajax 添加到购物车,您还需要将其添加到您的 JS 文件中:

$('body').on( 'added_to_cart', function(){
    if( ! $(this).hasClass('has_items') ) {
        // do something
    }
});
于 2019-07-05T15:18:01.660 回答