允许客户仅购买定义的 WooCommerce 产品类别中的一种产品
我想让客户只购买指定类别中的一种产品。所有产品的价格均为 0(零)。仅收取送货费。
我参考了相同的场景并尝试了这段代码。但对于未登录的用户,此代码会失败。当我尝试多次购买时,我就没有购买的想法。想要在第一次成功尝试购买后进行限制。我正在使用子主题 functions.php
文件。
注意:客户在购买前无需在网站上注册。
add_filter('woocommerce_add_to_cart_validation','filter_add_to_cart_validation',20, 2);
function filter_add_to_cart_validation($valid, $product_id){
$current_user = wp_get_current_user();
if ( wc_customer_bought_product( $current_user->user_email, $current_user->ID, $product_id) && has_term( array('free-giveaway'), 'product_cat', $product_id ) ) {
wc_add_notice( __( 'You already bought an item. Let others to buy as well.', 'woocommerce' ), 'error' );
$valid = false;
}
return $valid;
}
I want to let customers buy only one product from a defined category. All products are priced as 0 (zero). Only delivery fee is charged.
I referred to the same scenario and tried this code. But this code fails for not logged in users. When I try multiple purchases I have no matter of buying. Want to limit after the first successful attempt of a purchase. I am using the child theme functions.php
file.
Note: customers do not need to register in the website before doing a purchase.
add_filter('woocommerce_add_to_cart_validation','filter_add_to_cart_validation',20, 2);
function filter_add_to_cart_validation($valid, $product_id){
$current_user = wp_get_current_user();
if ( wc_customer_bought_product( $current_user->user_email, $current_user->ID, $product_id) && has_term( array('free-giveaway'), 'product_cat', $product_id ) ) {
wc_add_notice( __( 'You already bought an item. Let others to buy as well.', 'woocommerce' ), 'error' );
$valid = false;
}
return $valid;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
与答案相关的解释/评论:
has_bought()
函数被复制并粘贴自检查客户是否已经在 WooCommerce 中购买了东西答案代码所以您得到:
Explanation/comments related to the answer:
has_bought()
function is copied and pasted from Checking if customer has already bought something in WooCommerce answer codeSo you get: