How to Alter the WordPress Main Loop
In this tutorial, we show you the technique for altering the WordPress main loop on the homepage. We take the example of wanting to exclude a certain category from being displayed in the main loop.
Suppose here in my WordPress dashboard, I have five posts in various categories and one of them is uncategorized. The main WordPress loop that displays on the blog main page will show all five posts, provided that you have “Settings -> Reading -> Blog Post Show At Most” set to a number 5 or greater. Here is how to change the number of post per page if you need to.
We will show you how to exclude a certain category from the WordPress loop. This requires edit of the functions.php template file to add the following at the bottom …
add_action( 'pre_get_posts', 'exclude_cat_homepage' ); function exclude_cat_homepage($query) { if ( $query->is_home() && $query->is_main_query() && !is_admin() ) { $query->set( 'cat', '-8' ); } }
We are using the pre_get_posts hook to excludes category 8 (in our case, the Humor category) from being displayed in the WordPress main loop. The minus in front of the category id of 8 tells it to exclude this category.
The $query->is_home() make sure we are on the home page.
The $query->is_main_query() make sure we are applying only to the main query.
The !is_admin() make sure we do not apply this in the admin backend.
Why Not Use query_posts?
While we could have gotten the same results by putting …
query_posts(“cat=-8”);
before the main loop and resetting it with …
wp_reset_query();
after the main loop in index.php template file. It is not recommended because of reasons here and here.
How to Determine Category ID
How did we know that “Humor” category has category id of 8? We went to “Posts -> Categories” and hover over the “Edit” link for that category and noted the id in the URL query string as shown …
You can also click the “Edit” link and look for the id in the URL of the resulting page.
Exclude Uncategorized Posts from WordPress Loop
Doing the same, we can exclude any posts that are uncategorized. Typically, the uncategorized category is id 1. Hence …
$query->set( 'cat', '-1' );
Exclude Multiple Categories from WordPress loop
You can exclude multiple categories as well by separating the ids by commas. For example, the following excludes the Humor category as well as the uncategorized posts …
$query->set( 'cat', '-1,-8' );