WooCommerce每周只允许购买一次
问题描述:
我正在创建一个电子商务网站。我可以在我的主题的functions.php文件中添加什么,以允许客户只从商店购买一种产品,然后在1周内禁用任何其他购买?WooCommerce每周只允许购买一次
客户可以购买任何产品,但购买后,一周内不能再购买任何产品。客户只能在一周后进行其他任何购买。
我只能禁止使用此代码对产品进行购买:
add_filter('woocommerce_add_cart_item_data', 'woo_allow_one_item_only');
function woo_allow_one_item_only($cart_item_data) {
global $woocommerce;
$woocommerce->cart->empty_cart();
// Do nothing with the data and return
return $cart_item_data;
}
$customer_orders = get_posts(array(
'numberposts' => -1,
'meta_key' => '_customer_user',
'meta_value' => get_current_user_id(),
'post_type' => wc_get_order_types(),
'post_status' => array('wc-pending', 'wc-processing', 'wc-on-hold', 'wc-completed'),
));
// Order count
$order_count = 1;
if (count($customer_orders) >= $order_count) {
add_filter('woocommerce_is_purchasable', false);
}
答
更新:与WC增加兼容性+3
我应该更好地利用迷上自定义函数woocommerce_add_to_cart_validation
过滤器钩将允许产品添加到购物车之前检查您的条件是否满足。
这里是代码:
add_filter('woocommerce_add_to_cart_validation', 'conditionally_allowing_product_added_to_cart', 10, 3);
function conditionally_allowing_product_added_to_cart($passed, $product_id, $quantity) {
// If cart is not empty, customer will not be allowed and a notice will be displayed
if(! WC()->cart->is_empty()){
wc_add_notice('You can only add an item to cart', 'error');
$passed = false;
return $passed; // Not Allowed
} elseif(! is_user_logged_in()){ // When user is not logged in
$passed = true;
return $passed; // Allowed
} else {
$customer_orders = wc_get_orders($args = array(
'numberposts' => -1,
'meta_key' => '_customer_user',
'meta_value' => get_current_user_id(),
'post_status' => array('wc-pending', 'wc-processing', 'wc-on-hold', 'wc-completed'),
));
$customer_orders_count = count($customer_orders);
if(! empty($customer_orders_count) || $customer_orders_count > 0){
foreach($customer_orders as $customer_order){
// Added compatibility with WC +3
$order_date = method_exists($customer_order, 'get_date_created') ? $customer_order->get_date_created() : $customer_order->post->order_date;
// Stores each order timestamp in an array
$orders_time[] = strtotime($order_date);
}
// Sorting orders timestamps
sort($orders_time);
// Get the last timestamp (last date/time)
$last_order_time = end($orders_time);
$week = 7*24*60*60; // a week in seconds
// "Now" timestamp
$now_time = strtotime('now');
// Allowed time limit for customer to make a new order
$new_order_allowed_time = $last_order_time + $week;
if($now_time >= $new_order_allowed_time){
$passed = true; // Allowed
} else {
// Display a notice when customer is not allowed yet
wc_add_notice('You are not allowed yet to add any product in cart', 'error');
$passed = false; // Not Allowed
}
}
return $passed;
}
}
的代码放在你的活跃儿童主题(或主题)的function.php文件或也以任何插件文件。
此代码已经过测试并可正常工作。
我尝试了一个新用户,但现在我甚至不能进行我的第一次购买。首次购买时,我收到错误“您尚未在购物车中添加任何产品”。请帮忙。谢谢。 – Abhi
@Abhi我忘记了这种情况...我的代码将被更新。回来5分钟。你可以用现有的用户测试它... – LoicTheAztec
@Ahi我已经更新了我的答案... – LoicTheAztec