WordPress Tutorial: How to Exclude Specific Categories from the Homepage

wordpress exclude categoryhide specific categories homepagewordpress functions.php tutorialexclude post categorieswordpress custom query
Published·Modified·

Tutorial Introduction

Today, I had an idea that my site theme is suitable for videos, so I wanted to create a page on my blog that only displays my favorite videos, without showing articles on the homepage. I decided to get started immediately. This is a plugin-free code solution. Let's follow Chen Xinwei to see the results.

Before Testing

The test article needs to be hidden from the homepage but displayed in the specified category directory.

WordPress Tutorial: How to Exclude Specific Categories from the Homepage

Operation Method

First, Modify index.php

<?php if ( have_posts() ) : query_posts($query_string.'&cat=-1,-2');while ( have_posts() ) : the_post(); ?>

I originally planned to set rules within the loop in index.php, but after setting it, there was an issue with incomplete display counts on the homepage. I then thought about adding it to functions.php and then setting up a loop.

Second, Modify functions.php

To exclude specific categories from the WordPress homepage, add the following code to your functions.php file and save it. Reminder: It is recommended to use FTP and professional code editing software to make changes, and remember to backup your files!

function exclude_category_home( $query ) {  
    if ( $query->is_home ) { // Check if it is the homepage  
        $query->set( 'cat', '-1, -2' );  // IDs of the categories to exclude  
    }  
    return $query;  
}  
    
add_filter( 'pre_get_posts', 'exclude_category_home' );

Method 2 using this approach will not cause any page gaps, and the excluded content will not appear in the latest posts. Simply add the script above to your current theme's functions.php and modify the corresponding category IDs to exclude.

cat -1 -2

What does cat -1 -2 mean? It refers to the IDs of your category directories. If you only want to hide one category directory, use cat -2. I won't explain further; if you have questions, you can contact Chen Xinwei's Blog.

WordPress Tutorial: How to Exclude Specific Categories from the Homepage

See the Results

WordPress Tutorial: How to Exclude Specific Categories from the Homepage

WordPress Tutorial: How to Exclude Specific Categories from the Homepage

Original source: WordPress Tutorial: How to Exclude Specific Categories from the Homepage. All rights reserved by the original author. If there is any infringement, please contact QQ: 337003006 for deletion.