WordPress Tricks: How to exclude a certain category of posts from the loop

Use this line of code to control which categories of posts do and don’t show up in the loop for particular pages on your WordPress site:

<?php
if (is_page('recipes')) {
 $catID=4;
}
elseif (is_home()) {
 $catID=-4;
}
if ($catID) {
 $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
 query_posts("cat=$catID&paged=$paged");
} ?>

Copy and paste that code into your index.php or page.php template file, just before the loop is called.

This line of code will display all posts in category 4 on the recipe page, and not on the main blogroll page.

Simply change the page IDs (or slugs, either one will work) and the category IDs to control which pages show which category of posts.

To exclude a category of posts from the loop on a certain page, simply put a negative sign ( – ) in front of the category ID you want to exclude from that page, and the page will show posts from all categories except for that one.

If you want to specify which page each category of posts show up on, you would use this:

<?php
$catID = 0;
if (is_page('Books')) {
 $catID=1;
}
elseif (is_page('Videos')) {
 $catID=4;
}
elseif (is_page('CDs')) {
 $catID=5;
}
if ($catID) {
 $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
 query_posts("cat=$catID&paged=$paged");
} ?>

 

Let me know if you have any questions, need more help,  or run into any problems.

Related Posts:

One Response to “WordPress Tricks: How to exclude a certain category of posts from the loop”

  1. [...] See the original post here: WordPress Tricks: How to exclude a certain category of posts from … [...]

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">