woocommerce conditional products/categories on user role

Looking for a plugin that helps me to restrict woocommerce products or product categories based on role.

Let’s say that I only want to sell bulk products to whole sale buyers.

Read More

Any help is awesome, thanks!

Related posts

3 comments

  1. Here is how I managed to hide products based on role:

    First, I have added a checkbox in the product options inventory section to enable admins to hide the products based on their selection:

    add_action( 'woocommerce_product_options_stock_status', 'hide_if_available_to_user_role' );
    
    function hide_if_available_to_user_role(){
        woocommerce_wp_checkbox( array( 'id' => '_hide_from_users', 'wrapper_class' => 'show_if_simple show_if_variable', 'label' => __( 'Hide this product from specific roles?', 'customhideplugin' ) ) );
    }
    

    I then saved this selection in the actual post when a post is updated.

    add_action( 'woocommerce_process_product_meta', 'hide_save_product_meta' );
    
    function hide_save_product_meta( $post_id ){
        if( isset( $_POST['_hide_from_users'] ) ) {
            update_post_meta( $post_id, '_hide_from_users', 'yes' );
        } else {
            delete_post_meta( $post_id, '_hide_from_users' );
        }
    }
    

    This is how I got current user’s role.

    function getCurrentUserRole( $user = null ) {
        $user = $user ? new WP_User( $user ) : wp_get_current_user();
        return $user->roles ? $user->roles[0] : false;
    }
    

    Now query products. If the current user role matches the roles below, show the products as usual.
    Otherwise, set the query based on the code above…

    add_action( 'woocommerce_product_query', 'hide_product_query' );
    
    function hide_product_query( $q ){
    
      if((getCurrentUserRole() == 'editor' ) || (getCurrentUserRole() == 'administrator' )){
    
    return false;
    } else  {
    
    
    $meta_query = $q->get( 'meta_query' );
    
        if ( get_option( 'woocommerce_hide_out_of_stock_items' ) == 'no' ) {
            $meta_query[] = array(
                        'key'       => '_hide_from_users',
                        'compare'   => 'NOT EXISTS'
                    );
        }
    
        $q->set( 'meta_query', $meta_query );
    
    }
    
    
    }
    
  2. To achieve this you can use the Free Groups plugin. But for that you must add all the wholesalers to one group say wholesale group 1. Then while editing any product you get an option to access to, add the wholesaler group 1 there. The product will now be only seen by the user who is in wholesalers group 1.

Comments are closed.