Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marklchaves/ebef7bcde31f1d9034d6d05a3a6c3dbb to your computer and use it in GitHub Desktop.
Save marklchaves/ebef7bcde31f1d9034d6d05a3a6c3dbb to your computer and use it in GitHub Desktop.
WooCommerce: Exclude the Test product category from shop page except for admins and testers.
<?php
/**
* Exclude test products from a particular category on the shop page
* for non admins and non testers.
*
* I.e., only let admins and testers see test products.
*
* Reference: https://docs.woocommerce.com/document/exclude-a-category-from-the-shop-page/
*/
function custom_pre_get_posts_query( $q ) {
if ( is_user_logged_in() ) {
$user = wp_get_current_user();
$user_role = $user->roles[0];
if ( ( $user_role === 'administrator') || ( $user_role === 'tester' ) ) {
return;
}
}
$tax_query = (array) $q->get( 'tax_query' );
$tax_query[] = array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => array( 'test' ), // Don't display products in the test category on the shop page.
'operator' => 'NOT IN'
);
$q->set( 'tax_query', $tax_query );
}
add_action( 'woocommerce_product_query', 'custom_pre_get_posts_query' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment