Brain Food for Web Developers

Wordpress Folder

Exclude Category from WordPress Blog Page

Often when designing WordPress themes you’ll want to exclude a category from your blog page. Luckily it’s very easy to do.

Open up your index.php file (or whichever file you’re using to display your blog posts) and add this line of code right before the loop:

<?php query_posts('cat=-12'); ?>

Add the code right before this line:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

This will exclude the category with id of 12.

If you want to exclude more than one category you can use:

<?php query_posts('cat=-4,-12,-14'); ?>

Include a specific category

If you only want to include a certain category you just remove the minus character from the query:

<?php query_posts('cat=12'); ?>

Additional arguements

You can also add additional arguments to the query. In this example I will only display posts from a specific category and time period:

<?php query_posts('cat=12&year=2012'); ?>

You can take this a step further and only display posts from the current month by adding some php:

<?php query_posts( $query_string . '&cat=13&monthnum=' . date( 'n', current_time( 'timestamp' ) ) ); ?>

There are plenty of other arguments available to further filter your posts. Read more from the WordPress Codex: Query Posts.

Author: Graham

My name is Graham and I'm a Scottish web developer living in California. I love working with clean code to make attractive and usable websites. I'm also interested in cooking, gardening, and taekwondo.

Comments are closed.