問題描述

我正在使用 Woocommerce 外掛來方便一個站點的小型 e-commerce 部分,並且需要透過一些呼叫或功能將產品新增到它的購物車,而不是使用它自己的’add-to-cart’ 按鈕。

透過這個我基本上是指傳送 Woocommerce 一個 SKU 和數量,並有購物車更新。

sendToCart('123456', 55);

等等

我已經看過檔案,似乎找不到這種事情的參考。任何人都可以建議我如何實現這一點?

最佳解決方案

好的,所以這裡是我最後解決的。一個快速而骯髒的例子,使用 JQuery 。

<a id="buy" href="#">Buy this!</a>
    <script>    
       $('#buy').click(function(e) {
          e.preventDefault();
          addToCart(19);
          return false;
       });    

       function addToCart(p_id) {
          $.get('/wp/?post_type=product&add-to-cart=' + p_id, function() {
             // call back
          });
       }
    </script>

這只是一個 AJAX GET 請求到購物車的 URL

/wp/?post_type=product&add-to-cart=[PRODUCT_ID]

次佳解決方案

在 PHP 中,我設法這樣做:

global $woocommerce;
$woocommerce->cart->add_to_cart($product_id);

該方法是在 woocommerce / classes / class-wc-cart.php 中:

    /**
     * Add a product to the cart.
     *
     * @param string $product_id contains the id of the product to add to the cart
     * @param string $quantity contains the quantity of the item to add
     * @param int $variation_id
     * @param array $variation attribute values
     * @param array $cart_item_data extra cart item data we want to pass into the item
     * @return bool
     */
    public function add_to_cart( $product_id, $quantity = 1, $variation_id = '', $variation = '', $cart_item_data = array() ) {

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。