StackTips
 2 minutes

How to filter posts from WordPress home page archive

By Editorial @stacktips, On Sep 17, 2023 Wordpress 2.24K Views

The landing page of most of the news or personal blogging sites usually display the recent posts achieve of the blog unless the front page is set to a static html page. Your blog might have many different categories, but could be annoying to users who just want to show the recent posts from specific categories to appear on home page recent posts. The following code snippet will help you to do that.

Add the following snippet to your WordPress theme functions.php file to exclude the posts from selected category to appear on WordPress home page archive.

//filter homepage categories
add_action('pre_get_posts', 'ad_filter_categories');
function ad_filter_categories($query) {
    if ($query->is_main_query() && is_home()) {
        $query->set('category_name','slug1, slug2, slug3');
    }
}
stacktips avtar

Editorial

StackTips provides programming tutorials, how-to guides and code snippets on different programming languages.