Wordpress Woocommerce - 使用WC_Cart类将可变产品添加到购物车

Gga*_*Gga 9 php wordpress

我正在尝试将可变产品添加到Wordpress插件Woocommerce的购物车中.

到目前为止,我已经能够添加单/简单产品:

$woocommerce->cart->add_to_cart( [product_id], [quantity] );
Run Code Online (Sandbox Code Playgroud)

但是,在函数签名中查看WC_Class:

function add_to_cart( $product_id, $quantity = 1, $variation_id = '', $variation = '', $cart_item_data = array() ) {
Run Code Online (Sandbox Code Playgroud)

我们可以清楚地看到函数允许变量_id的输入.

我已尝试过以下行的每个空值和整数组合:

$woocommerce->cart->add_to_cart( 24, 1, 28, null, null ); 
Run Code Online (Sandbox Code Playgroud)

等等无济于事.

我也试过自己的hacky方法试图重新创建由Woocommerce自己的产品页面发布的帖子事件,再次没有运气.

<a id="buy_v" href="#">Buy Variable Product !</a>    
<script>    
   $('#buy_v').click(function(e) {
      e.preventDefault();
      addToCartV(24,26,'Red',1);
      return false;
   });    
   function addToCartV(p_id, v_id, c, q) {    
    $.ajax({
      type: 'POST',
      url: '/wp/?product=tee1&add-to-cart=variation&product_id='+p_id,
      data: { 'attribute_colour': c,
              'variation_id':  v_id,
              'quantity':  q,
              'product_id':  p_id},
      success: function(response, textStatus, jqXHR){
            // log a message to the console
            console.log("It worked!");
        }/*,
      dataType: 'JSON'*/
    });    
   }   
</script>
Run Code Online (Sandbox Code Playgroud)

谁能建议我哪里出错了?谢谢.

Gga*_*Gga 13

以上示例实际上都工作正常,它们只是在Woocommerce自己的购物车中无法正确显示.

要使它们正确显示,请为第四个参数传入一个数组,该数组似乎代表了Woocommerce自己的购物车中的变体:

$arr = array();
$arr['Color'] = 'Green';
$woocommerce->cart->add_to_cart( 24, 1, 28, $arr, null ); 
Run Code Online (Sandbox Code Playgroud)