簡體   English   中英

以編程方式添加到購物車時,自動“刷新” woocommerce的購物車

[英]Automatically 'refreshing' the woocommerce's shopping cart when programmatically adding to a cart

我在wordpress中使用woocommerce。

我正在使用以下命令在頁面之一中顯示購物車:

 <div id="shopping-cart"><?php echo do_shortcode('[woocommerce_cart]');?></div>

當用戶使用以下代碼單擊按鈕時,我正在使用自己的功能將產品添加到此購物車:

 function addToCart(p_id){
     alert("Adding to cart:"+p_id);
      jQuery.get('/wordpress/?post_type=product&add-to-cart=' + p_id, function(response) {
             // call back
             alert(response);
          });

         //jQuery("#shopping-cart").append("[woocommerce_cart]"); 
           alert("Added to cart:"+p_id);
    }

我通過以下代碼調用此javascript:

 <button type="button" onclick="return addToCart(18);">Add to cart</button>

該代碼可以工作,但使用a_shortcode創建的購物車在ajax請求完成后不會更新。

有人可以告訴我如何在獲取請求完成后自動更新購物車嗎?

救援文件 :)

// Ensure cart contents update when products are added to the cart via AJAX (place the following in functions.php)
add_filter('add_to_cart_fragments', 'woocommerce_header_add_to_cart_fragment');

function woocommerce_header_add_to_cart_fragment( $fragments ) {
    global $woocommerce;
    ob_start();
?>
<a class="cart-contents" href="<?php echo $woocommerce->cart->get_cart_url(); ?>" title="<?php _e('View your shopping cart', 'woothemes'); ?>"><?php echo sprintf(_n('%d item', '%d items', $woocommerce->cart->cart_contents_count, 'woothemes'), $woocommerce->cart->cart_contents_count);?> - <?php echo $woocommerce->cart->get_cart_total(); ?></a>
<?php
    $fragments['a.cart-contents'] = ob_get_clean();
    return $fragments;
}

您可能需要調整HTML以適合您的設計。

嘗試在“添加到購物車”警報后添加此代碼...

location.reload(); 

最后,我創建一個Ajax調用,該調用調用了PHP函數,該函數返回了調用do_shortcode('[woocommerce_cart]');的結果。 然后我將它清空后放到同一個div中-效果很好:)

我必須通過woocommerce使用Ajax來實際獲得PHP中的do_shortcode調用才能成功運行,如下所示:

http://codex.wordpress.org/AJAX_in_Plugins

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM