Display products from specific category in shop page

The shop page is actually an archive page for posts of type ‘product’. Its template is in woocommerce/archive-product.php.

You need to use the pre_get_posts action to preprocess the query before the loop, conditional_tags to recognize that you are in the product archive page, and a taxonomy query to filter the product categories, which belong to the taxonomy ‘product_cat’.

For example, the following (placed in your theme’s functions.php or in a plugin) will display only products with product category ‘type-1’:

 add_action('pre_get_posts','shop_filter_cat');

 function shop_filter_cat($query) {
    if (!is_admin() && is_post_type_archive( 'product' ) && $query->is_main_query()) {
       $query->set('tax_query', array(
                    array ('taxonomy' => 'product_cat',
                                       'field' => 'slug',
                                        'terms' => 'type-1'
                                 )
                     )
       );   
    }
 }

You can also exclude categories by using ‘operator’ => NOT IN, and ‘terms’ can be an array of product category slugs.

A good introduction to query customization is http://www.billerickson.net/customize-the-wordpress-query/

Leave a Comment

error code: 523