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

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!