Buzzslot, Web trends, internet strategy, design, blogging

Inside the loop: Style posts differently

category: Snippets

In many sites (like this one) we want multiple loops in our home page (mostly). We can achive that easily. But what happens when we want the first post of our loop to become emphasized, the last to have some special class or we want to have some ad code after the third post?

So we have to load our normal query for a category and for our example 4 posts. As you can see, in line 2 and 4 we added the counting php code. Then for the first and the fourth article we put an if and added the different divs that we want, our posts to be in.

The same way we can add an ad block at the end of the first post (line 12).

<?php $my_query = new WP_Query('cat=10&showposts=4'); ?>
<?php $count = 0; ?>
<?php while ($my_query->have_posts()) : $my_query->the_post(); $do_not_duplicate = $post->ID; ?>
<?php $count++; ?>

	<?php if ($count == 1) : ?>
		<div id="featured">
			<h2 class="clear"><a href="<?php the_permalink(); ?>" ><?php the_title(); ?></a></h2>
			<p class="clear"><?php the_content('read more...'); ?></p>
		</div>
		<hr/>

	<?php elseif ($count == 4) : ?>
		<div class="last">
			<h3><a href="<?php the_permalink(); ?>" ><?php the_title(); ?></a></h3>
			<p class="clear"><?php the_content('read more...'); ?></p>
		</div>

	<?php else : ?>
		<div class="border">
			<h3><a href="<?php the_permalink(); ?>" ><?php the_title(); ?></a></h3>
			<p class="clear"><?php the_content('read more...'); ?></p>
		</div>

	<?php endif; ?>
<?php endwhile; ?>

2 Responses to “Inside the loop: Style posts differently”

  1. Mai Dwyer says:

    thank you for posting are there feeds to your blog? I’d like to subscribe

  2. Thanks for your comment! At the top of the sidebar, is a link to WPspecial’s RSS


Leave a Reply