Я хотел бы создать скрипт для автоматического добавления бонусного продукта в корзину WooCommerce.WooCommerce - Автоматически добавлять бонусный продукт
Бонусный продукт будет добавлен в корзину при добавлении определенного продукта (ов). Но я никогда не видел улучшенный и полностью работающий код с функциями - например, автоматически удаляя бонусный предмет или удаляя основной товар (ы) из корзины.
В этом решении я пришел с ниже код, который имеет следующие характеристики:
- опции
- Несколько необходимых продуктов
- долив
- Автоматическое не снимая (если есть нет требуемый продукт в корзине)
function bonus_product() {
if (is_admin()) return;
//## OPTIONS
$options = (object) array(
'bonus_product_id' => 1891, //bonus product to add
'required_products_id' => array(1873), //at least on of the specific product(s) needs to be represented in the cart
);
//function variables
$cart_items = WC()->cart->get_cart();
$bonus_product_found = false;
$required_product_found = false;
//check if the cart is not empty
if(sizeof($cart_items) > 0) {
//checking for required products. loop through the cart items
foreach ($cart_items as $key => $item) {
//bonus product already in the cart?
if($item['product_id'] == $options->bonus_product_id) {
$bonus_product_found = true;
}
//one of required products in the cart?
if(in_array($item['product_id'], $options->required_products_id)) {
$required_product_found = true;
}
}
//adding/removing bonus product
//add bonus product to the cart
if(!$bonus_product_found && $required_product_found) {
WC()->cart->add_to_cart($options->bonus_product_id);
}
//remove bonus product from the cart if none of required items is in the cart
if($bonus_product_found && !$required_product_found) {
$cart = WC()->instance()->cart;
$cart_id = $cart->generate_cart_id($options->bonus_product_id);
$cart_item_id = $cart->find_product_in_cart($cart_id);
$cart->set_quantity($cart_item_id, 0);
}
}
}
add_action('init', 'bonus_product');
Спасибо. Это здорово! –
@the_ousek Если это сработало, примите ответ. – Sark