In this tutorial we’ll learn how to remove/hide products of a category page from shop page. To do this first of all create some products and assign them to categories. I’ve created two products, two categories and assigned one product to each category.
This will be my shop page look like after products creation and assignation with the category.
Now, let’s say I want to remove products of one category i.e. category 2 from shop page.
To do this, add the following lines of code at the end of your function.php file:
add_action( 'pre_get_posts', 'custom_pre_get_posts' ); functioncustom_pre_get_posts( $q ) { if ( ! $q->is_main_query() ) return; if ( ! $q->is_post_type_archive() ) return; if ( ! is_admin() &&is_shop() ) { $q->set( 'tax_query', array(array( 'taxonomy' => 'product_cat', 'field' => 'slug', 'terms' => array( 'category-2'), // Don't display products in the private-clients category on the shop page 'operator' => 'NOT IN' ))); } remove_action( 'pre_get_posts', 'custom_pre_get_posts_query' ); }
Replace the category slug of the category in the terms’ array with the category slug you want to remove/hide products for.
Place the code, save file and refresh the shop page. You’ll see the products in defined category has been removed.
Thank you! I used this on my coffee website to hide private products I use to raise money for different charities.
There were some minor syntax errors in your code though. Such as not having a space after “function” and after “&&”. But after I fixed those it worked great!
Thank you for the correction.