![](/img/trans.png)
[英]Get cart item variation name instead of variation ID in WooCommerce
[英]Check if this Variation ID exists in cart, then add another item to cart
如果將此變體 ID 添加到購物車,我正在嘗試弄清楚如何將特定項目添加到購物車。 例如,我有一個可配置產品的 4 個變體。
11264 11265 11266 11267
如果產品變體 11264 和 11265 添加到購物車,則產品 ID 111 的產品也應添加到購物車。 如果將 11266 和 11267 添加到購物車,則產品 ID 為 222 的產品也應添加到購物車。
我在網上找到了這個代碼,可以根據產品類別將項目添加到購物車:
function aaptc_add_product_to_cart( $item_key, $product_id ) {
$product_category_id = 123; // cricket bat category id
$product_cats_ids = wc_get_product_term_ids( $product_id, 'product_cat' );
if ( ! is_admin() && in_array( $product_category_id, $product_cats_ids ) ) {
$free_product_id = 1522; // Product Id of the free product which will get added to cart
$found = false;
//check if product already in cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->get_id() == $free_product_id )
$found = true;
}
// if product not found, add it
if ( ! $found )
WC()->cart->add_to_cart( $free_product_id );
} else {
// if no products in cart, add it
WC()->cart->add_to_cart( $free_product_id );
}
}
}
add_action( 'woocommerce_add_to_cart', 'aaptc_add_product_to_cart', 10, 2 );
該代碼按預期工作。 但現在我想讓它有條件。 所以我修改了這一行:
if ( ! $found )
WC()->cart->add_to_cart( $free_product_id );
並將其更改為:
if ($found && WC()->cart->(11264,11265))
WC()->cart->add_to_cart(111);
因此,如果購物車中存在變體 ID 11264 或 11265,則添加產品 ID 111。我認為我的語法錯誤,但我不確定下一步是什么。 嘗試谷歌搜索幾個小時,但我找不到任何像樣的例子。
在 foreach 循環中稍作修改以獲取和比較變化可能會解決問題
foreach( WC()->cart->get_cart() as $cart_item_key => $values ) {
$variation_ids = array(11264,11265);
//check if variation exist in cart & if found add product in cart with ID 111
if( in_array( $values['variation_id'], $variation_ids ) ) {
WC()->cart->add_to_cart(111);
}
else {
//Do something
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.