In my header I already have an option that will show the number of items in my cart, that will change every time I click on add to cart button. I also have total amount, but that won’t add up as I add products to cart. In my header is
<?php if( in_array('woocommerce/woocommerce.php', get_option('active_plugins')) ):?>
<p id="shop_links" class="cart_right"><?php _e('Cart:','theme') ?>
<a class="link_cart" href="<?php echo $woocommerce->cart->get_cart_url(); ?>">
<span>
<?php
echo '<span class="items_count">' . $woocommerce->cart->cart_contents_count . '</span> ' ._n('item', 'items', $woocommerce->cart->cart_contents_count ,'theme') . ' ' . '— ' . $woocommerce->cart->get_cart_total() ;
?>
</span>
<i class="icon-shoppingbag"></i>
</a>
</p>
<?php endif; ?>
My button has class .add_to_cart_ajax
and the code that works for number of items in cart is
$('.add_to_cart_ajax').click(function(e){
e.preventDefault();
var $this = $(this);
var product_id = $this.data('product_id');
var added_title = $this.data('added_title');
var $shop_links = $('#shop_links');
var $cart_no = $shop_links.find('.link_cart span .items_count');
var $cart_amount = $shop_links.find('.link_cart span .amount');
var currentPrice = $this.parents('li.product').find('.price ins .amount , .price > .amount').text();
var data = {
action: 'theme_add_to_cart_wishlist',
product_id: product_id,
add_to: 'cart'
};
$.post(ajaxurl, data, function(response) {
$cart_no.text(parseInt($cart_no.text())+1);
$cart_amount.text(parseFloat($cart_amount.replace(/[.,](?=.*[.,])/g, "").replace(",", ".").text())+currentPrice.replace(/[.,](?=.*[.,])/g, "").replace(",", "."));
if(!$this.hasClass('in-cart')){
$this.addClass('in-cart').tipsy("hide").attr("original-title",added_title).tipsy("show");
}
});
});
But the part $cart_amount
doesn’t do what I’d like it to do (add price as I click on various products). I tested with console.log
when I click on the add to cart button I get the right price out. So what am I missing?
I find a solution of sorts
This seems to be woorking, for some reason I couldn’t update the price with the ajax one. This will do.