Last active
September 6, 2021 09:48
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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