Custom cart count is not updating without reloadin

2019-07-18 03:57发布

I have the ajax script enqueued, but I can't seem to get the cart items count updated without refreshing the page.

Functions:

// Add scripts and stylesheets
function startwordpress_scripts() {
    wp_enqueue_style( 'reset', get_template_directory_uri() . '/reset.css' );
    wp_enqueue_style( 'style', get_template_directory_uri() . '/style.css' );
    wp_enqueue_style( 'style', get_template_directory_uri() . '/veggiee.css');
    wp_enqueue_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js', array(), null, true);
}

function woocommerce_header_add_to_cart_fragment( $fragments ) {
    global $woocommerce;

    ob_start();

    $fragments['a.cart-customlocation'] = ob_get_clean();
    return $fragments;
}
add_filter( 'woocommerce_add_to_cart_validation', 'is_product_the_same_cat', 10, 3 );

HTML:

<ul>
<li>
<a href="/cart" id="cart_icon"></a></li><li><span class="counter"> 
<?php echo sprintf ( _n( '%d', '%d', WC()->cart>get_cart_contents_count() ), WC()->cart->get_cart_contents_count() ); ?></span></li>
<li id="access"><?php wp_nav_menu( array( 'sort_column' => 'menu_order', 'container_class' => 'menu-header' ) ); ?></li>
</ul>

I have researched the problem and as far as I can see the basket total should update straight away without a refresh.

Does anyone have any idea what I'm missing here?

1条回答
时光不老,我们不散
2楼-- · 2019-07-18 04:43

There is some mistakes and missing things in your code. For the cart item count in your header the following will solve the problem.

1) The HTML code in your header.php file:

<ul>
    <li>
        <a href="/cart" id="cart_icon"></a>
    </li>
    <li>
        <span class="counter" id="cart-count"><?php
        $cart_count = WC()->cart->get_cart_contents_count();
        echo sprintf ( _n( '%d', '%d', $cart_count ), $cart_count );
        ?></span>
    </li>
    <li id="access"><?php wp_nav_menu( array( 'sort_column' => 'menu_order', 'container_class' => 'menu-header' ) ); ?></li>
</ul>

2) Your related hooked function code to enable cart item count Ajax refreshed:

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 sprintf ( _n( '%d', '%d', $cart_count ), $cart_count );
    ?></span>
    <?php
     $fragments['#cart-count'] = ob_get_clean();

    return $fragments;
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.


Related: Ajaxify the cart items count in Woocommerce

查看更多
登录 后发表回答