phpwordpresswoocommercecheckoutorders

Restrict customers to buy once per year In WooCommerce


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


Solution

  • I fixed the error and now it works, here is the final coding in case someone needs it:

    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( 'U' );
                $current_time = current_time( 'U', true );
                $year_in_sec = 60 * 60 * 24 * 365;
                $seconds_passed = $current_time - $date_created;
                $last_order_created = $last_order->get_date_created()->format( 'M d, Y' );  
    
                if ( $seconds_passed < $year_in_sec ) {
                    wc_add_notice( sprintf( '<b>ONLY ONE PURCHASE IS ALLOWED WITHIN 365 DAYS. </b><br>Your last order was on %1$s. Please try again when the 365 day period has been reached. ', $last_order_created, $day_in_sec, $seconds_passed ), 'error' );
                 remove_action( 'woocommerce_proceed_to_checkout','woocommerce_button_proceed_to_checkout', 20);
                }
            }
        }
    }
    add_action( 'woocommerce_check_cart_items', 'new_order_allowed' );