restriction to buy once per year woocommerce, date is not working

  Kiến thức lập trình

I’m using this coding to restrict the users to create an order per year, and it’s working well. But, I noticed that if the date created of the last order is more than 365 days, the coding takes it as it was from this year so it doesn’t let users that have purchased with more than 365 days to buy again. Can someone please review the coding and make the necessary modifications? Thanks in advance!

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' );

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT