我使用此编码来限制用户每年创建订单,并且效果良好。但是,我注意到,如果最后一个订单的创建日期超过 365 天,编码会采用今年的日期,因此不会让购买时间超过 365 天的用户再次购买。有人可以检查编码并进行必要的修改吗?预先感谢!
function new_order_allowed() {
if( ! ( is_cart() || is_checkout() ) ) return;
if ( is_user_logged_in() ) {
$user_id = get_current_user_id();
$last_order = wc_get_customer_last_order( $user_id );
if ( $last_order ) {
$date_created = $last_order->get_date_created()->format( 'z' ) + 1;
$current_time = current_time( 'z', true ) + 1;
$year_in_day = 365;
$days_passed = $current_time - $date_created;
if ( $days_passed < $year_in_day ) {
wc_add_notice( sprintf( '<b>ONLY ONE PURCHASE IS ALLOWED WITHIN 365 DAYS. </b><br>Your last order was %1$s days ago. Please try again when the 365 day period has been reached. ', $days_passed ), 'error' );
remove_action( 'woocommerce_proceed_to_checkout','woocommerce_button_proceed_to_checkout', 20);
}
}
}
}
add_action( 'woocommerce_check_cart_items', 'new_order_allowed' );
为什么不以简单的方式来做呢?
$dateFrom = new DateTime('2023-05-01');
$dateTo = new DateTime('2024-05-01');
echo $dateFrom->diff($dateTo)->days;
这样
$dateFrom->diff($dateTo)->days;
将为您返回两个日期之间的天数。
尝试以下基于时间戳的修改后的代码:
add_action( 'woocommerce_check_cart_items', 'new_order_allowed' );
function new_order_allowed() {
if ( is_user_logged_in() && ( is_cart() || is_checkout() ) ) {
$last_order = wc_get_customer_last_order( get_current_user_id() );
if ( is_a( $last_order, 'WC_Order') ) {
$created_timestamp = $last_order->get_date_created()->getTimestamp();
$allowed_timestamp = strtotime('-1 year');
$days_difference = floor(($created_timestamp - $allowed_timestamp) / DAY_IN_SECONDS);
$days_passed = 365 - $days_difference;
if ( $created_timestamp <= $allowed_timestamp ) {
wc_add_notice( sprintf(
__('<strong>ONLY ONE PURCHASE IS ALLOWED WITHIN 365 DAYS.</strong><br>Your last order was made %s days ago. Please try again when the 365 day period has been reached.'),
$days_passed ), 'error' );
remove_action( 'woocommerce_proceed_to_checkout','woocommerce_button_proceed_to_checkout', 20);
}
}
}
}
应该可以。