Site icon Qaisar Satti's Blogs

How to Allow Product Purchase to Customer Once in a Lifetime

Today we are going to talk about How to Allow Product Purchase to Customer Once in a Lifetime. You have to paste the following function in your active/child theme’s function.php file.

add_action( 'woocommerce_add_to_cart', 'qaisarsatti_checknumberoforder', 999);
function qaisarsatti_checknumberoforder() {
    global $woocommerce;

    if ( is_user_logged_in() ) {
        $userId = get_current_user_id();
       
       $args = array(
            'customer_id' => $userId,
            'post_status' => 'wc-completed',
            'post_type' => 'shop_order',
            'return' => 'ids',
        );
        $allOrders = count( wc_get_orders( $args ) );


        if ($allOrders > 1) {
            //empty the cart
            WC()->cart->empty_cart( true );
            wc_add_notice( __( 'We have removed the product from your cart.', 'woocommerce' ), 'notice' );
            wp_redirect( get_permalink(get_option('woocommerce_myaccount_page_id')));
           
        }
    }
}
Exit mobile version