Exclude products from a particular category on the shop page in WooCommerce

Here’s a handy WordPress code snippet, which allows you to exclude or hide products from a particular category on the shop page in WooCommerce.

Useful Read: Change placeholder image | WooCommerce

To exclude products from shop, paste the following code snippet in your functions.php file.

//Exclude products from a particular category on the shop in WooCommerce
add_action( 'pre_get_posts', 'custom_pre_get_posts_query' );
function custom_pre_get_posts_query( $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( 'mobile','laptop' ),
			'operator' => 'NOT IN'
		)));
	}
	remove_action( 'pre_get_posts', 'custom_pre_get_posts_query' );
}

 Note:  Replace ‘mobile’ and ‘laptop’ with slug of categories you want to remove.

0 Comments

Leave a Comment.