Restrict woocommerce product to certain customer to buy

谁说我不能喝 提交于 2019-12-10 11:59:06

问题


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.


回答1:


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.




回答2:


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)



来源:https://stackoverflow.com/questions/44326772/restrict-woocommerce-product-to-certain-customer-to-buy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!