At times, you may want to hide certain product categories from appearing on your shop page. This could be due to various reasons: seasonal product lines, out-of-stock items, or simply to streamline your user’s browsing experience. The following PHP code snippet can help you achieve this with ease:

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( 'specific-category', 'specific-category-slug2' ), // Don't forget to replace 'specific-category' with your category slug
            'operator' => 'NOT IN'
        )));
    }
    remove_action( 'pre_get_posts', 'custom_pre_get_posts_query' );
}

This code works by hooking into the 'pre_get_posts' action, which is a WordPress core action that allows you to alter the main query before it is executed. By modifying this query, we can define certain conditions that posts must meet to be included in the results.

The function custom_pre_get_posts_query checks whether the current page is the main query and post type archive. If both conditions are satisfied, it checks whether the page is not an admin page and is a shop page. If these conditions are met, it sets a tax query to exclude a specific category (defined by slug) from appearing on the shop page.

Remember to replace 'specific-category' with the slug of the category you wish to exclude.

To implement this code snippet, add it to your child theme’s functions.php file or a custom plugin. Adding code to a child theme or a custom plugin ensures that your changes will not be overwritten when the parent theme updates.

Here’s how to do it:

  1. For a child theme: Open your child theme’s functions.php file and add the code there. If you don’t have a child theme, consider creating one to prevent your modifications from being lost when the parent theme updates.
  2. For a custom plugin: If you prefer not to use a child theme, you can create a simple custom plugin and add the code there.