简体   繁体   中英

Restrict woocommerce product to certain customer to buy

I am setting up an eCommerce website selling household's stuff. I'd like some products to be purchased by regular visitors but some products (with lots of discounts) are retricted to certain Memberships only (namely wholesalers) and these products shows to every visitors but when a regular visitor clicks on "add to cart", it will re-direct to a membership registeration form with a note: Only wholesale member are allowed to purchase this item. I am building a woocomerce multilingual website using WPML. Please suggest codes or plugin that I should use for this project.

Thank you very much.

I would start by taking a look at this plugin:

https://en-ca.wordpress.org/plugins/user-role-editor/

It will allow you to create a new user role - for your specific 'wholesalers'. I would then add a custom category of products to classify which products you'd like to only be available to wholesale members. With those two pieces of information, you can then do a check like this:

function custom_wholesale_add_to_cart_redirect(){
    global $post;
    $terms = get_the_terms( $post->ID, 'product_cat' );
    foreach ($terms as $term) {
        if('wholesale' == $term->slug){
            $user = wp_get_current_user();
            if ( !in_array('wholesale', (array)$user->roles) || !is_user_logged_in() ){
                wp_redirect('your-redirect-page');
                exit;
            }
        }
    }
}

add_action('woocommerce_add_to_cart', 'custom_wholesale_add_to_cart_redirect');

You're checking the current product - if it is part of the 'wholesale' category, then check the current user - and if that user is not a 'wholesale' member - or not logged in - redirect to your page.

I had to find solution today and best way imho is to use this plugin: https://wordpress.org/plugins/product-visibility-by-user-role-for-woocommerce/

Only downside, free version is fully manual (no batch changing for all products at once). But you can block buying of that product, hide it completely and some other settings.

I used https://wordpress.org/plugins/user-role-editor/ for creating user category. (as in the other answer)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM