WordPress: Exclude A Category From The Front Page Without Breaking Pagingation

in Tutorials & Samples/Web Development/Wordpress

There are many reasons why you may want to exclude a certain category from your main loop in WordPress. For example, on this site, I exclude my blog entries from my portfolio entries. In order to exclude a category from the list of posts that appear on your homepage, you can use the WordPress function query_posts(). query_posts() is a way to alter the main query that WordPress uses to display posts. It does this by putting the main query to one side, and replacing it with a new query. However, it is up to you to handle pagination when using query_posts or you will only show the first page of posts for every page.

Excluding a category from the main loop

The following is a simple example of how to exclude a category from your query in index.php.

<?php
if ( is_home() ) {
	query_posts( 'cat=-3' );
}
?>

Placing this code in the index.php file will cause the home page to display posts from all categories except category ID 3. If you wanted to exclude multiple categories, you can also do the following:

<?php
if ( is_home() ) {
	query_posts( 'cat=-1,-2,-3' );
}
?>

However, using this function as-is will break WordPress’ pagination!. So, you will never see the following pages other than the first page of the posts result and you will be simply showing the same page over and over again. Page two, page three and so on will show exactly the same posts as on page one.

Excluding a category from the main loop and keeping pagination in WordPress

In order to exclude a category from your main loop in index.php and display contents of the other pages, you need to specify the include the paged parameter in your query_posts() arguments. The following is an example of how to do so:

<?php
if ( is_home() ) {
	$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
	query_posts( 'cat=-3&paged=' . $paged );
}
?>

The function get_query_var() will check to see if the variable paged is defined. Now, with this new version of the query, you are excluding all posts from category 3, but you are also checking to see what page you are on so that you can show the posts that belong to that page…

Tags:

Mifty Yusuf is a Montreal-based software developer who enjoys playing with new web technologies as well as comic books and illustrations. He beleives that, no matter what the question is, the answer is always Batman!

2 Comments

Leave a Reply

Your email address will not be published.

*

Latest from Tutorials & Samples

Go to Top