Home / eCommerce / Show Certain Products to Certain Wholesale Customers Only
Duplicate Snippet

Embed Snippet on Your Site

Show Certain Products to Certain Wholesale Customers Only

How to use:
1. Do not tag normal/default products.
2. Tag only “special” products with "wholesale-special".
3. Put those products’ SKUs under the correct user IDs in $extra_skus_by_user (e.g. SKU4, SKU5 for user 85 and SKU6, SKU7 for user 53).

Code Preview
php
<?php
add_action( 'pre_get_posts', function ( WP_Query $query ) {
    // Only affect frontend main product queries (shop, category, etc.)
    if ( is_admin() || ! $query->is_main_query() || 'product' !== $query->get( 'post_type' ) ) {
        return;
    }
    $user_id = get_current_user_id();
    // Admins / shop managers see everything
    if ( user_can( $user_id, 'manage_woocommerce' ) || user_can( $user_id, 'manage_options' ) ) {
        return;
    }
    static $default_product_ids = null;
    if ( null === $default_product_ids ) {
        // All published products
        $all_products = wc_get_products(
            array(
                'status' => 'publish',
                'limit'  => -1,
                'return' => 'ids',
            )
        );
        // Products that have the wholesale-special tag
        $special_products = wc_get_products(
            array(
                'status'       => 'publish',
                'limit'        => -1,
                'return'       => 'ids',
                'tag'          => array( 'wholesale-special' ), // tag slug
                'tag_operator' => 'IN',
            )
        );
        // Default = all products EXCEPT those tagged wholesale-special
        $default_product_ids = array_diff( $all_products, $special_products );
    }
    // Start with default products (shown to guests, regular, and most wholesale users)
    $allowed_ids = $default_product_ids;
    // Extra SKUs for specific wholesale customers
    if ( user_can( $user_id, 'wholesale_customer' ) ) {
        $extra_skus_by_user = array(
            85 => array( 'SKU4', 'SKU5' ),
            53 => array( 'SKU6', 'SKU7' ),
        );
        if ( isset( $extra_skus_by_user[ $user_id ] ) ) {
            foreach ( $extra_skus_by_user[ $user_id ] as $sku ) {
                $product_id = wc_get_product_id_by_sku( $sku );
                if ( $product_id ) {
                    $allowed_ids[] = $product_id;
                }
            }
        }
    }
    $allowed_ids = array_unique( array_filter( $allowed_ids ) );
    // Apply restriction (guests + regulars already covered by $default_product_ids)
    if ( $allowed_ids ) {
        $query->set( 'post__in', $allowed_ids );
    } else {
        $query->set( 'post__in', array( 0 ) ); // nothing visible
    }
} );

Comments

Add a Comment