首页 > 解决方案 > 购物车计数未在移动设备 woocommerce 中更新

问题描述

我正在使用此代码更新 woocommerce 中的购物车计数以更新 woocommerce 购物车。它在较大的设备中正常工作。但在移动设备中不工作。刷新后它工作。我在下面附上代码。

在functions.php中这是代码

add_filter( 'woocommerce_add_to_cart_fragments', 'refresh_cart_count', 50, 1 );
function refresh_cart_count( $fragments ){
    ob_start();
    ?>  
    <span class="counter" id="cart-count"><?php
    $cart_count = WC()->cart->get_cart_contents_count();       
    echo $cart_count;
    ?></span>
    
    <?php
     $fragments['#cart-count'] = ob_get_clean();     
    return $fragments;
}

在大型设备和移动设备的 header.php 购物车部分

<li>

                   <a href="<?php echo get_template_directory_uri(); ?>/cart"

                      ><i class="uil uil-shopping-cart-alt"></i> Cart</a

                    >
                    <span class="counter" id="cart-count-mobile"><?php
    $cart_count = WC()->cart->get_cart_contents_count();
    
    echo $cart_count;
    ?></span>


              </li>

这是在大型设备和移动设备中对购物车重复 2 次的相同代码。

标签: woocommerce

解决方案


在functions.php 中使用类名而不是id.it 会起作用。

add_filter( 'woocommerce_add_to_cart_fragments', 'refresh_cart_count', 50, 1 );
function refresh_cart_count( $fragments ){
    ob_start();
    ?>
   
    <span class="counter" id="cart-count"><?php
    $cart_count = WC()->cart->get_cart_contents_count();   
    echo $cart_count;
    ?></span>
    
    <?php     
    $fragments['span.counter'] = ob_get_clean();    
    return $fragments;
}

推荐阅读