Loop the (WordPress) Loop

Somewhat recently, a client asked to create a way for visitors to submit content and rank said content for a site he was creating, much like the sites found on the cheezburger.com network. The site is powered by WordPress, so I installed and configured TDO Mini Forms for visitors to submit stuff, and GD Star Rating for the rating system. The site would have the posts in chronological order on a page, and the front page would have content ordered by ranking.

In the end, the front page simply displays content by ranking, which is easily accomplished with a page template and query_posts() with the GD Star Rating plugin’s parameters. My first attempt was over-engineered a bit for the client’s liking and was scrapped for the former option, but I thought it was a rather clever way of displaying posts – placing the WordPress loop within a loop.

I realize this has been done before, but here’s my twist on it:

<?php if (have_posts()) :
$daysBack = '0';
while ( $daysBack >= -7 ) :
$dateRange = getdate(strtotime($daysBack . "days"));
query_posts('year=' .$dateRange["year"] .'&monthnum=' .$dateRange["mon"] .'&day=' .$dateRange["mday"] .'&gdsr_sort=thumbs&gdsr_order=desc&showposts=1' );
<?php while ( have_posts() ) : the_post(); ?>
Do loop stuff...
<?php endwhile; // End the loop. Whew. ?>
<?php $daysBack--; ?>
<?php endwhile; ?>

Basically what this does is takes a look back through the last 7 days worth of posts, selects the highest-rated from each day, and displays them. Neat, huh?

So you may ask, “what if the site becomes derelict or just doesn’t get new content after a while…what then smart guy? The page won’t display any posts!” Sheesh, lay off! I already thought of this:

<?php rewind_posts(); ?>
<?php query_posts('orderby=rand&showposts=1'); ?>
<?php while (have_posts()) : the_post(); ?>
Do loop stuff again!
<?php endwhile; ?>
<?php endif; ?>
<?php wp_reset_query(); ?>

Further down on the page, we display a random post. Now the front page will display at least one post, and at most 8 posts. Oh snap!

Of course, this isn’t a fully complete solution. We should modify the second loop so that it does not display a post already displayed above, to avoid duplicating content. Even though this is incomplete and was scrapped in favor of just showing posts by rank and completely ignoring chronology, I thought it was a neat solution and thought I would share for anyone who may be interested.

Leave a Reply

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