Php WooCommerce-为选定产品的一次购买促销获得免费产品
我有一个商业网站。我想为一些选定的产品添加一个类似“买1送1”的促销活动 我该怎么做Php WooCommerce-为选定产品的一次购买促销获得免费产品,php,wordpress,woocommerce,cart,product,Php,Wordpress,Woocommerce,Cart,Product,我有一个商业网站。我想为一些选定的产品添加一个类似“买1送1”的促销活动 我该怎么做 谢谢是的,没有插件也可以。有不同的方法,但最好且简单的方法是……基于产品类别和50%的自动应用优惠券(简单且更好) 1) 首先在后端产品>类别中创建产品类别,例如“two4one” 将此类别设置为您希望拥有此促销计划的所有产品(一个2个) 2) 在woocommerce中创建特殊优惠券(自动应用): 在woocommerce中,创建一张优惠券,您可以将其命名为'2for1'您将对其进行以下特殊设置: 常规>折
谢谢是的,没有插件也可以。有不同的方法,但最好且简单的方法是……基于产品类别和50%的自动应用优惠券(简单且更好) 1) 首先在后端产品>类别中创建产品类别,例如“two4one”
将此类别设置为您希望拥有此促销计划的所有产品(一个2个) 2) 在woocommerce中创建特殊优惠券(自动应用):
在woocommerce中,创建一张优惠券,您可以将其命名为
'2for1'
您将对其进行以下特殊设置:
- 常规>折扣类型:产品%折扣
- 常规>息票金额:
(这是一个百分比,见上一行)50
- 使用限制>仅限个人使用:已启用
- 使用限制>产品类别:
(在此处添加您的特殊产品类别)two4one
two4one
类别产品。如果从购物车中删除所有包含two4one类别的产品,优惠券也将被删除
3)代码:一旦优惠券创建并正确设置,您就可以使用此挂钩函数代码:
// Add to Cart 2 products at the same time of the "two4one" product category
add_action( 'woocommerce_add_to_cart', 'add_to_cart_qty_by_two', 10 );
function add_to_cart_qty_by_two($cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data) {
// When a product has 'two4one' as category increment quantity by one (2 products)
if( has_term( 'two4one', 'product_cat', $product_id ) ) {
$quantity += $quantity;
WC()->cart->set_quantity($cart_item_key, $quantity);
}
}
// Auto applying coupon if products with two4one" category are in cart
add_action( 'woocommerce_before_calculate_totals', 'auto_add_a_coupon_discount', 10 );
function auto_add_a_coupon_discount( $cart_object ) {
foreach ( $cart_object->cart_contents as $key => $item ) {
// When a product has 'two4one' as category auto apply coupon '2for1'.
if( has_term( 'two4one', 'product_cat', $item["product_id"] ) && !$cart_object->has_discount('2for1') )
WC()->cart->add_discount('2for1');
}
}
// If customer discrease or increse quantity it will be restored to an even number on checkout
add_action( 'woocommerce_before_checkout_form', 'checking_promotional_products', 10 );
function checking_promotional_products() {
foreach ( WC()->cart->cart_contents as $item_key => $item ) {
// if it's a promo product category and quantity is an even number
if( has_term( 'two4one', 'product_cat', $item["product_id"] ) && $item["quantity"] % 2 != 0 ) {
// checking that item quantity is always an even number (if not adds 1)
$quantity = $item["quantity"] + 1;
WC()->cart->set_quantity($item_key, $quantity);
}
}
}
此代码位于活动子主题(或主题)的function.php文件或任何插件文件中。很少有插件可以这样做。LoicTheAztec:非常好的解决方案,我也在考虑如何在没有任何插件的情况下做到这一点,但我并没有想到这个解决方案。我从过去两周一直在关注你,通过阅读你的答案,我学到了很多。谢谢你这么好的回答。@LoicTheAztec不为我工作。请再举一个例子