WordPress WooCommerce - 使用 WC_Cart 类将可变产品添加到购物车 [英] WordPress WooCommerce - Add a variable product to cart using the WC_Cart class
问题描述
我正在尝试将可变产品添加到 WordPress 插件 WooCommerce 的购物车中.
I am trying to add a variable product to the cart of the WordPress plugin, WooCommerce.
到目前为止,我已经能够添加单个/简单的产品:
So far I have been able to add single/simple products with:
$woocommerce->cart->add_to_cart( [product_id], [quantity] );
但是,查看 WC_Class 中的函数签名:
However, looking in the WC_Class at the functions signature:
function add_to_cart( $product_id, $quantity = 1, $variation_id = '', $variation = '', $cart_item_data = array() ) {
我们可以清楚地看到该函数允许输入variation_id.
we can clearly see the function permits inputs of variation_id.
我已经尝试了以下行的空值和整数的每种组合:
I have tried every combination of nulls and integers along the lines of:
$woocommerce->cart->add_to_cart( 24, 1, 28, null, null );
等等都无济于事.
我也尝试过我自己的hacky方法,试图重新创建由WooCommerce自己的产品页面执行的发布事件,但没有成功.
Ive also tried my own hacky approach that tries to recreate the post events performed by WooCommerce's own product page, again with no luck.
<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>
有人可以建议我可能出错的地方吗?谢谢.
Could anyone suggest where I might be going wrong? Thanks.
推荐答案
上面的两个例子实际上都运行良好,只是在 WooCommerce 自己的购物车中没有正确显示.
Both the above example actually work fine, they just don't display correctly in WooCommerce's own cart.
为了使它们正确显示,请为第四个参数传递一个数组,该参数似乎代表 WooCommerce 自己的购物车中的变化:
To make them display correctly, pass in an array for the forth parameter which seems to represent the variation in WooCommerce's own cart:
$arr = array();
$arr['Color'] = 'Green';
$woocommerce->cart->add_to_cart( 24, 1, 28, $arr, null );
这篇关于WordPress WooCommerce - 使用 WC_Cart 类将可变产品添加到购物车的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!