wordpresswoocommerceproductorderspurchase-order

Allow woocommerce product to purchase for selected customer only


My requirement is that, i want to Allow to allow only selected customer can purchase some particular products. Other customer can't buy that product.

I have that all customer email ID list. When at checkout time that customer add their email ID on billing address then if that email ID match with admin side mail ID then only allow to purchase that product.

But front end side on check out page and my account page i have disable login and registration. So all customer is guest. So with out user role restriction how it's possible?

Any one know this solutions then please help me.

Thanks.


Solution

  • You can try this code, it will restrict other users for purchasing on your site. It will only allow customers on your email id list to purchase,

    add_action( 'woocommerce_after_checkout_validation' , 'add_user_email_restriction', 10, 2 );
    
    function add_user_email_restriction( $data, $errors ) {
    
        $valid_emails = get_available_email_addresses();
        // should be in array format
    
        if( isset( $data[ 'billing_email' ] ) && !empty( $data[ 'billing_email' ] ) ) {
            if( !in_array( $data[ 'billing_email' ], $valid_emails ) ) {
                $errors->add( 'email', __( 'You are not allowed to purchase.', 'text-domain' ) );
            }
        }
    }
    function get_available_email_addresses() {
        return array('test@gmail.com','test2@gmail.com');
    }