是否有人有 woocommerce 结帐验证的示例,如果他们在过去 30 天内已经购买了 2 种产品,我可能会失败验证?
我似乎找到的只是输入字段的 javascript 验证,但我最好在 PHP 中完成更复杂的验证。
非常感谢!
您可以使用 woocommerce
woocommerce_checkout_process
钩子来防止。将此代码添加到您的活动主题functions.php 文件中。
function prevent_users_from_buying_more_than_two_products_per_month() {
$user_id = 0;
if ( is_user_logged_in() ) {
$user_id = get_current_user_id();
} else {
$user_email = isset($_POST['billing_email']) ? sanitize_email($_POST['billing_email']) : '';
$user = get_user_by('email', $user_email);
if ($user) {
$user_id = $user->ID;
}
}
if( $user_id ){
$max_products_allowed = 2;
$thirty_days_ago = date('Y-m-d H:i:s', strtotime('-30 days'));
$args = array(
'post_type' => 'shop_order',
'post_status' => 'wc-completed', // Only consider completed orders
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => '_customer_user',
'value' => $user_id,
'compare' => '=',
),
array(
'key' => '_completed_date',
'value' => $thirty_days_ago,
'compare' => '>',
'type' => 'DATE',
),
),
);
$query = new WP_Query($args);
$num_products_purchased = $query->post_count;
if ($num_products_purchased >= $max_products_allowed) {
wc_add_notice('You have already purchased ' . $num_products_purchased . ' products in the last 30 days.', 'error');
}
}
}
add_action('woocommerce_checkout_process', 'prevent_users_from_buying_more_than_two_products_per_month ');