仅当在 Woocommerce 中应用优惠券时才允许购买特定产品

编程入门 行业动态 更新时间:2024-10-26 12:23:09
本文介绍了仅当在 Woocommerce 中应用优惠券时才允许购买特定产品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在 woocommerce 网站上工作,我试图限制只有在申请了优惠券后才能购买的产品,因此在不添加优惠券代码的情况下不应对其进行处理.用户必须输入优惠券代码才能订购此特定产品(而非所有其他产品).

I am working on a woocommerce website and I am trying to restrict a product to be purchased only if a coupon is applied for it, so it should not be processed without adding a coupon code. User must enter a coupon code to be able to order this specific product (not on all other products).

感谢任何帮助.

推荐答案

对于定义的产品,如果没有应用优惠券,以下代码将不允许结帐,显示错误消息:

For defined products, the following code will not allow checkout if a coupon is not applied, displaying an error message:

add_action( 'woocommerce_check_cart_items', 'mandatory_coupon_for_specific_items' ); function mandatory_coupon_for_specific_items() { $targeted_ids = array(37); // The targeted product ids (in this array) $coupon_code = 'summer2'; // The required coupon code $coupon_applied = in_array( strtolower($coupon_code), WC()->cart->get_applied_coupons() ); // Loop through cart items foreach(WC()->cart->get_cart() as $cart_item ) { // Check cart item for defined product Ids and applied coupon if( in_array( $cart_item['product_id'], $targeted_ids ) && ! $coupon_applied ) { wc_clear_notices(); // Clear all other notices // Avoid checkout displaying an error notice wc_add_notice( sprintf( 'The product"%s" requires a coupon for checkout.', $cart_item['data']->get_name() ), 'error' ); break; // stop the loop } } }

代码位于活动子主题(或活动主题)的 functions.php 文件中.经测试有效.

Code goes in functions.php file of your active child theme (or active theme). Tested and works.

结帐时:

更多推荐

仅当在 Woocommerce 中应用优惠券时才允许购买特定产品

本文发布于:2023-10-12 20:56:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1485873.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:优惠券   时才   产品   Woocommerce

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!