Fruit Loop: Separate any Number of Odd and Even Posts from any Category in WordPress

Published Sunday, November 16, 2008 @ 11:19 pm • 0 Responses

[ ~{*}~ ] Recently, I discussed how to implement a horizontally sequenced display order for WordPress posts in two columns. In that tutorial, I explain how to separate odd and even posts using a dual-loop configuration and PHP’s modulus operator. Such technique serves well a variety of configurational scenarios, but is limited to the display of the default (admin-specified) number of posts from all categories. In this tutorial, we adapt this odd-and-even loop configuration to accommodate a much greater degree of customization. Specifically, we will focus on separating any number of odd and even posts from any specific category or group of categories. Several additional configurational customizations will also be covered.

The Problem

In that previous dual-loop article I was telling you about, the dual-loop configuration is based upon two if(have_posts()):while(have_posts()): queries:

<?php if(have_posts()) : while(have_posts()) : 
      $i++; if(($i % 2) == 0) : $wp_query->next_post(); else : the_post(); ?>

<?php the_content(); ?>

<?php endif; endwhile; else: ?>
<!-- alternate content -->
<?php endif; ?>

<?php $i = 0; rewind_posts(); ?>

<?php if(have_posts()) : while(have_posts()) : 
      $i++; if(($i % 2) !== 0) : $wp_query->next_post(); else : the_post(); ?>

<?php the_content(); ?>

<?php endif; endwhile; else: ?>
<!-- alternate content -->
<?php endif; ?>

Unfortunately, this configuration does not allow us to easily customize additional parameters such as the number of posts displayed in each loop, the category/categories from which posts are displayed, the order in which posts are displayed, and many others. As-is, our dual-loop configuration separates odd posts from even posts using two loops; all posts are pulled from all available categories, and the total number of posts displayed is based upon the specified value in the “Reading” options page in the WordPress admin. For example, if your default number of displayed posts is ten, each loop would display five posts, depending on availability.

What we want to do in this tutorial involves adapting our even/odd, dual-loop setup to accommodate further customization of various loop parameters. By replacing the two if(have_posts()):while(have_posts()): queries with two query_posts() queries, we expand the functionality of our loop configuration to enable category filtering, post numbers, and much more.

The Solution

The solution is very straightforward; simply replace the first part of each loop:

if(have_posts()) :

With a query_posts() query:

query_posts();

Such that we arrive with this very similar dual-loop configuration:

<?php query_posts(); while(have_posts()) : ?>
<?php $i++; if(($i % 2) == 0) : $wp_query->next_post(); else : the_post(); ?>

<?php the_content(); ?>

<?php endif; endwhile; ?>

<?php $i = 0; rewind_posts(); ?>

<?php query_posts(); while(have_posts()) : ?>
<?php $i++; if(($i % 2) !== 0) : $wp_query->next_post(); else : the_post(); ?>

<?php the_content(); ?>

<?php endif; endwhile; ?>

Having done that, our odd/even dual-loop setup will continue to function as before, with the default number of posts being called from all categories and subsequently divided into odd and even posts via the two loops. The only difference at this point is that our new loop configuration is a lean, mean, highly customizable machine. We can now specify any number of posts, filter any number of categories, and do all of the other wonderful things made possible by the query_posts() function.

Customization

Now that we have modified our loop to accommodate customization of various parameters, let’s configure a dual-loop function that accomplishes the following:

  1. display only posts from category "x" in both loops
  2. display only ten posts in each loop, for a total of twenty posts
  3. display only odd posts in the first loop
  4. display only even posts in the second loop

To do this, we will use our custom loop setup and add two parameters to each of two query_posts() functions. As defined at the WordPress Codex, there are many parameters available to the query_posts() function, including the two we will use for this example:

  • cat=x
  • showposts=10

These parameters are self-explanatory. The cat=x parameter defines the category (remember to replace "x" with your category!), and the showposts=10 parameter defines the number of posts to be shown. Here is how these two parameters look when included properly into each of the query_posts() functions:

<?php query_posts('cat=x&showposts=10'); while(have_posts()) : ?>

And with that, we have accomplished our previously defined loop configuration. Ten category-"x" posts will be displayed in each loop, with odd posts appearing in the first loop and even posts appearing in the second loop. Of course, by simply modifying either or both of these two parameters, any number of posts may be called from any category, or even group of categories, as explained more fully in the WordPress Codex.

By taking advantage of the many other parameters available to the query_posts() function, the configurational possibilities are virtually endless. Here are just a few examples of the different parameter-based modifications you make to any query_posts-based loop:

  • tag=chevy,monza — display specific tag content
  • author_name=fonzi — display specific author content
  • day=, monthnum=, year= — display time-specific content
  • showposts=7 — specify any number of posts
  • 'post__in' => array(1,2,3) — display specific posts

As you can see, just about anything is possible when it comes to customizing the WordPress loop! For more great tips and tricks on WordPress loops, check out the “Related articles” section at the end of this tutorial. I also invite you to subscribe to Perishable Press for a periodic dose of WordPress, Web Design, and much more! :)

Mad Shouts

Huge thanks to Tony Boswell for his work with the primary technique covered in this tutorial. While implementing the odd/even, dual-loop configuration on his site, Sound Check Enterprises, Tony discovered the secret to customizing the method presented in my previous loop article: query_posts()! The query_posts() function enables extensive control over many key loop parameters, thereby enabling the various techniques presented in this article. Thanks for the eye-opener, Tony! :)



Share your thoughts..

TopRead official comment policy

Contact Perishable Press

  • Contact Jeff via form

Search Perishable Press

About Perishable Press

Perishable Press is the virtual playground of Jeff Starr — visionary, founder and lead developer of Monzilla Media, a small web and graphic design company in the lush desert oasis of Moses Lake, Washington. Perishable Press features articles and tutorials on many aspects of digital design..

Read more..

Perishable on Twitter

better to have too many ideas and not enough time than the converse

Perishable on Tumblr

WordPress Tip for Multiple Themes

Sunday, 4 January 2009, 5:16 pm

If your site makes available multiple themes for users to choose from, remember to include the JavaScript (or any other required code) for any statistical applications that you might be using, such as Mint, Google Analytics, and so forth. I am not sure about the various WordPress statistics plugins, but they may need to be included as well. A good way to check if your stats plugin is tracking data across all themes is to either visit a few pages that you know others aren’t hitting, or else activate each of the alternate themes and check the source code of each one for the required code.

Earlier today, I realized that only several of my most recent themes included the required JavaScript for Mint and Google Analytics. I am now in the process of editing each of the 18 themes available for users at Perishable Press. Haven’t decided on whether or not both statistics apps are needed for all themes, but I will certainly be using at least one of them to keep an eye on everything.

Insane Christmas

Monday, 22 December 2008, 9:47 pm

For as long as I can remember, Christmas has always been a relatively peaceful affair. Sure there’s the usual holiday stress — traffic, shopping, presents, relatives, and all that goes with the preparation of a traditional celebration, but when it’s all said and done, you get to relax and enjoy the peace and harmony of gathering together and basking in the reason for the season: the birth of Christ.

This year, however, the stress factor has been kicked up a few notches, making for a rather insane Christmas if I do say so myself. In addition to the usual holiday chaos, we are currently purchasing a brand new home, and quickly realizing the incredible amount of work involved in the process. If you’ve ever bought a newly built home, you know exactly what I am talking about here.

Plus, as if all the paperwork, inspections, insurance, costs, and anxious anticipation weren’t enough to confound the usual holiday stress, we are also packing up everything, dealing with kids, working full-time jobs, and — beginning on Christmas Eve — moving into our new house.

It certainly is all a great joy and blessing to have such amazing things going on, but combined with the work that I do on the Web — blogging, designing, projects, helping people, and so on — it really becomes all too much rather quickly. We are doing are best to get through everything with our sanity intact, but I have to admit that this is the most insane Christmas I have ever experienced.

New (4G) Blacklist Now in Beta

Monday, 22 December 2008, 9:27 pm

Just a quick note to anyone interested in securing their websites against malicious activity, spam, and other nonsense. Several months after releasing my 3G Blacklist, I have finally begun work on the next incarnation of the blacklist: the 4G Firewall!

The first part of the blacklist is now ready for testing, and I plan on setting it up on Perishable Press within the next few days. While testing on my own site, I thought it would beneficial to also invite a few “beta” testers to run the code on their own site(s) as well.

So, if you have a site that receives its share of malicious attacks, and cracker exploits, drop me a line via the contact form at Perishable Press and I will send you the initial block of HTAccess directives. This version of the Blacklist is looking better than ever, and I look forward to releasing the complete version to the public early in 2009.

Thanks for the Free Traffic and Link Juice

Sunday, 7 December 2008, 1:26 pm

Just wanted to thank the fine folks at fafich.ufmg.br for all the free traffic and link juice. Thanks to their misapplication of my comprehensive canonicalization code, every non-canonical version of their 21,700 indexed pages points directly to my site, Perishable Press. This means that every one of their permalink URLs that is mistyped, lacks the “www” prefix, or contains the superfluous “index.php” file name is directed via permanent redirect directly to the home page of my site.

I have tried contacting the site owner(s) about this situation, but it has been over a week and I have yet to hear anything back. Hopefully, they will take notice soon and correct the issue by properly configuring their htaccess file, but in the meantime, I certainly don’t mind the extra link juice and free traffic! :)

No Plugin Needed for Feed Delay

Monday, 24 November 2008, 10:01 am

I recently saw a WordPress plugin that was designed to delay the publication of your WordPress feed by any specified time interval. While it is a good idea to carefully proofread your content before posting it, a plugin certainly is not required to do so.

As savvy WordPress users already know, WordPress has a built-in post-preview feature that enables authors to view their unpublished content as a published post. This enables authors to do any amount of proofreading and browser checking until they are satisfied with the results.

To do this, simply write your post as usual, and then click on the “Preview this post” button on the right-hand side of the screen. In older versions of WordPress (less than 2.5, I think), you actually need to save (without publishing!) the post first and then re-open it as if to continue editing. You will then see a “Preview »” link sort of hidden (due to poor CSS design) in the upper-right corner near the edit post field. Right-click on that link to open in new tab and you are good to go.

No extra plugin needed! :)

Read more on Tumblr..

Subscribe to Comments Recent Dialogue

  • Chiwan: Hi. This is cool. So I can I replace the clock that comes with your Apathy theme with this clock? If that's not possible, how do ...
  • Brass Engraved: Thankyou very much for this, worked like a dream!...
  • Patrix: I'm using FeedBurner and the Feedsmith plugin for my filter blog, DesiPundit. I found your post via the WordPress page for RSS feeds ...
  • teddY: @Jessi Hance: Sorry to hear about your experience with Twitter spammers/flamers. I was once a victim of flamers and it sucks that peo...
  • heywho: Hey.... Very Nice...... I'm TOTALLY not a programmer..... but I have this thing I want to do...... so I just decided to start doi...
  • Rodrigo Nunes: NIce SEE MY BLOG http://designrn.wordpress.com/...
  • zubfatal: The Quintessential theme looks great to me, however when scrolling up or down on the page, it makes my laptop work harder than it sho...
  • Adrian van Vliet: Hah, great post Jeff. Nice to see something personal about the man behind Perishable, it really adds some perspective. I've added min...
  • Marcel: Hi, I found your blog entry trough the almighty Google and although it totally fits my needs, I found one 'problem' with this appr...
  • René Silva: I'm glad posts like this one, I also saw some people who follows everyone that seems to have an auto-follow script, so it's easy to b...

Read more recent comments..

Attention: Do NOT follow this link!