How to make custom total price reactive in navigation

I created navigation for my custom template and added total price inside the <li></li> elements and it show the price if I add product to the cart, but if I add another product to cart price not change automatically. If I want the price updated, I need to refresh the whole page.

Can someone help me to make this price updating automatically if I add products to cart? I’m very bad about ajax etc… but I want this to working like it should work.

<ul class="nav-link-right">
    <li class="nav-link-price">
          
          <?php if ( class_exists( 'Woocommerce' ) ) : ?>

          <?php 

          // Get order total 
          $cart_total = WC()->cart->get_cart_subtotal();

          ?>

          <span id="order-total-price"><?php echo $cart_total; ?></span>


    </li>
</ul>

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Using woocommerce woocommerce_add_to_cart_fragments filter you can do that.

Going by the id attribute that you currently have for the span that displays the cart total, you can use the following code

add_filter('woocommerce_add_to_cart_fragments', 'bt_update_cart_total');
function bt_update_cart_total ($fragments) {
    $fragments['#order-total-price'] = '<span id="order-total-price">' . WC()->cart->get_cart_subtotal() . '</span>';

    return $fragments;
}

Add this code to your functions.php file and thats it.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x