对于我的网上商店,我想发起一个折扣活动,在这个活动中,当购物车达到一定的总额时,我的客户免费获得正常付款的产品。无论购物车的价值多少,他们获得的产品仍然可用。
我不想创建该产品的变体,也不想创建一个新产品。我希望看到免费产品链接到现有的付费产品,但是购物车中的价格降低了(可能还有不同的标题)。
为更加清晰起见,我添加了一张图片作为演示。我在演示中将限值设置为60英镑。
有人知道我如何用PHP完成这项工作吗?我已经编写了以下代码,但这仅有助于将产品添加到购物车中。
# First of all, let us hook into the cart caclulation method.
add_action( 'woocommerce_after_calculate_totals', 'add_free_product_to_cart');
# This function will be responsible for the add/remove item from the cart, depending on the total value.
function add_free_product_to_cart() {
# We need this global WooCommerce variable in order to access the cart.
global $woocommerce;
## SETTINGS ##
$settings['product_id'] = 2981; // Change me to the specific product id you want to add to the cart.
$settings['cart_limit'] = 60; // Change me to set the specfic threshold.
## Some local variables we need in order to make this work ##
$found = false;
# Check if there are any items in the cart.
if (sizeof($woocommerce->cart->get_cart()) > 0)
{
# There are items in the cart. Lets loop trough them one by one and check for our specific product id.
foreach ($woocommerce->cart->get_cart() as $cart_item_key => $values)
{
$product_id_in_cart = $values['data']->get_id();
# We found the specific product id in the cart.
if ($product_id_in_cart == $settings['product_id'])
{
# Lets check if cart total has been changed in the meantime. We need to remove the product if the cart total is below the limit.
if ($woocommerce->cart->total < $settings['cart_limit'])
{
# Remove the product from the cart.
$woocommerce->cart->remove_cart_item($cart_item_key);
}
# We found our specific product id, we don't need to run more code at this point.
$found = true;
break;
}
}
# The specific product id has not been found, lets add it to the cart if the total has reached the limit.
if (!$found && $woocommerce->cart->total >= $settings['cart_limit'])
{
$woocommerce->cart->add_to_cart($settings['product_id']);
}
}
}