我在这里找到了这个:如果在 WooCoomerce 上从购物车中删除了产品 B,则从购物车中删除产品 A,当将产品 A 添加到购物车时,它可以添加产品 B。我正在使用 WPCode Snippet。
add_action( 'woocommerce_add_cart_item_data', function( $cart_item_data, $product_id )
{
//If added product ID is 67 then also add product with an ID of 15
if ( 67 == $product_id ) {
WC()->cart->add_to_cart( 15 );
}
}, 10, 2 );
但是,当两个代码都处于活动状态时,给出的答案不起作用。我有两个单独的代码片段。当我添加产品 A 时,它是购物车中的唯一商品。现在不添加产品B。两个代码是否都需要位于一个片段中(可能)?或者根本不起作用。另外,我需要使用 ID,因为我创建了一个电子学习网站,该网站不是 WooCommerce(产品 A),但产品 B 是 WooCommerce 产品。它使用 WooCommerce 购物车进行结帐。
add_action( 'woocommerce_remove_cart_item', 'jhall_remove_product_from_cart', 10, 2 );
/**
* Remove Product ID 15 when Product ID 67 is removed from the cart
*
* @param $item_key
* @param $cart
* @return $item_key
*/
function jhall_remove_product_from_cart( $item_key, $cart ){
//Get the ID of the product removed
$removed_id = $cart->cart_contents[$item_key]['product_id'];
//If the Product ID is 67
if( $removed_id === 67 ){
//You need a cart key for the product you want to remove
$remove_from_cart_product_id = $cart->generate_cart_id( 15 );
//Remove Product ID 15 from the cart
$cart->remove_cart_item( $remove_from_cart_product_id );
}
尝试以下代码替换:
add_action('woocommerce_before_calculate_totals', 'action_before_cart_calculate_totals');
function action_before_cart_calculate_totals( $cart ) {
if ((is_admin() && !defined('DOING_AJAX')))
return;
$targeted_product_id = 67; // Define the targeted product ID
$linked_product_id = 15; // Define the linked product ID that should be added (complementary)
$linked_item_key = $targeted_found = false; // Initialized variables
// Check cart items
foreach ( $cart->get_cart() as $item_key => $item ) {
// Check if our targeted product is in cart
if ( $item['product_id'] == $targeted_product_id ) {
$targeted_found = true;
}
// Check if the complementary product is in cart
elseif ( $item['product_id'] == $linked_product_id ) {
$linked_item_key = $item_key;
}
}
if ( $targeted_found && ! $linked_item_key ) {
$cart->add_to_cart( $linked_product_id ); // Add to cart the complementary product
} elseif ( ! $targeted_found && $linked_item_key ) {
$cart->remove_cart_item($linked_item_key); // Remove from cart the complementary product
}
}
代码位于子主题的functions.php 文件中(或插件中)。已测试并有效。