1. Home
  2. Knowledge Base
  3. WooCommerce Wholesale Pro
  4. Advanced Usage

Creating public-only product variations

If you are using WooCommerce Wholesale Pro, then the easiest way to set the visibility for each product is to restrict the categories to Public Only, Wholesale Only, or both. There's also a workaround that lets you show specific variations to wholesale users only.

However, it's less straightforward to show specific variations to public users only, while hiding them from logged in wholesale users. The only way to do this is to clone the product, use the category visibility to show one version of the product to public customers and the other for wholesale users, and add the appropriate variations to each one.

A customer has helpfully provided the below code snippet that will allow you to do this programmatically. We are sharing this in the hope that it helps other people too, but this code is aimed at developers who know how to use it, and does not come under our plugin support.

We've partnered with Codeable to provide our customers with expert help if required.

Code snippet

The following code snippet is aimed at developers and will run for users with a wholesale role. It removes any variations that do not have a wholesale price set. You can add it to the functions.php file in your theme or child theme.

<?php
function custom_woocommerce_dropdown_variation_attribute_options_html( $html, $args ) {

if( in_array( 'wcwp_wholesale', (array) wp_get_current_user()->roles ) ){
$arguments = array(
'post_type' => 'product_variation',
'post_status' => array( 'private', 'publish' ),
'numberposts' => -1,
'orderby' => 'menu_order',
'order' => 'asc',
'post_parent' => get_the_ID() // get parent post-ID
);
$variations = get_posts( $arguments );

foreach ( $variations as $variation ) {

$variation_ID = $variation->ID;
//Get variation meta data based on the variation ID
$product_variation = new WC_Product_Variation( $variation_ID );
//get variation title
$variation_attributes = $product_variation->get_variation_attributes();
// get variation wholesale price
$wholesale_price = get_post_meta( $variation_ID , 'wcwp_wholesale', true );

if ( empty($wholesale_price)) {
$html = str_replace( '<option value="' . esc_attr( $variation_attributes['attribute_pa_products'] ) . '" ', '<option hidden value="' . esc_attr( $variation_attributes['attribute_pa_products'] ) . '" ', $html );
}

}//end variation foreach

}//end user role
return $html;
}
add_filter( 'woocommerce_dropdown_variation_attribute_options_html', 'custom_woocommerce_dropdown_variation_attribute_options_html', 10, 2 );

Related Articles

If searching the knowledge base hasn't answered your question, please contact support.