Removing a product category from the Shop page

You may have some products that you don't want to advertise to the entirety of your audience. Maybe they're products that only apply to one gender, or products that are only good for someone of a certain age, or some other niche product that doesn't make sense for your whole audience. If you make sure that the products appearing on the shop page apply to everyone, that will keep your conversion rates high.

How to do it…

To remove a product category from the Shop page, we'll have to modify the query to the database. We can use some of the hooks built into WordPress to modify the query rather than writing an entirely new one, which is a huge time-saver. Let's perform the following steps to remove a product category:

  1. In your code editor, open up your theme's functions.php file or a custom WooCommerce plugin.
  2. At the bottom of the file, add the following code:
    add_action( 'pre_get_posts', 'woocommerce_cookbook_pre_get_posts_query' ); 
    function woocommerce_cookbook_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( 'posters' ), 'operator' => 'NOT IN' ))); 
        } 
        remove_action( 'pre_get_posts', 'woocommerce_cookbook_pre_get_posts_query' ); 
    }
  3. You'll need to change the posters in the code to the slug of the category you wish to exclude. If you want to exclude multiple categories, you should comma-separate them and make sure that each one is enclosed in single quotation marks. For example, 'category-1', 'cat-2', 'cat3'.

    Note

    If you don't know the slug of the category you wish to exclude, you can see the full list in the WordPress admin under Products | Categories.

  4. Upload and save the file.

How it works…

This code is run right before WordPress queries the database. The first part checks to make sure we're modifying the right query you wouldn't want to accidentally break your blog page. Once we know we're only modifying the right query, we tell WordPress to ignore certain product categories. And that's it. It takes a bit of code to do what we want to do, but it's pretty simple.

There's more…

You could modify all types of queries and all sorts of things with queries. You could, for example, have a shop page that only shows featured products that were released in the last month. But queries of this type are very advanced and you'll probably need a developer to help you with that sort of thing.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset