michael’s thoughts

collected

Excluding Categories from The Loop with WordPress Template Tags

When I redesigned this site’s WordPress theme, I decided I wanted to show the most two recent posts at the top followed by the next 8 posts with just the title and a link to the post, so that the front page does not scroll forever.  That’s simple enough to do with the template tag query_posts(), but I ran into an unexpected problem with my initial approach and the Twitter Tools plugin.

Initially I had the code as:

<?php query_posts('showposts=8?offset=2'); ?>

Simple enough, but I am using the wonderful Twitter Tools plugin to automatically create a daily post with my tweets.  Because I tweet more frequently than I update this blog, the list of older posts was dominated by twitter updates.

I wanted the list to show only actual blog posts, not twitter updates.  So I changed the code to be as follows:

<?php query_posts('showposts=8?offset=2?cat=-54'); ?>

Category 54 is my twitter category, so this would grab 8 non-twitter updates.  But it turns out, this didn’t work either.  The problem was that the offset and category filters start from the top, so if my second most recent post was a twitter post it would filter that out, and then offset from 2, which would mean that if the third most recent post was not a twitter update it wouldn’t show up at all.  Not what I wanted.

So I tried changing the offset to 1, but that doesn’t work because if the most recent updates are not twitter updates then it will show the second post twice – once in long form and once in the older posts section.

So I again changed my query_posts() call to look like:

<?php query_posts('offset=2'); ?>

and then added in some logic in The Loop to manually filter out twitter posts using the in_category() template tag:

 <?php if ( in_category(54) ) {
} else { ?>
...show the post link...

Sadly I lose the ability to keep it at a constant 8 posts, although I could change the code again to grab some large number of posts and keep a counter and manually break from The Loop once I’ve actually displayed the 8 post links.  But I’m happy with how it’s working for now.

Just thought I’d share this, since it took me a few minutes to find the correct template tags to make this work.

blog comments powered by Disqus