How to modify the standard loop of posts in Wordpress

Thursday, July 17, 2008 11:29
Posted in category Tech&Internet

Wordpress uses the loop to fetch the posts from the database and visualize them in the right page.
But what to do if you want to break the rules of the loop and style each post differently or if you want to insert ads and so on?
Here is how I styled my loop to make only the first post show the full content while only the excerpt for the others. The following code resolves the problem of showing only the excerpt for all the older posts when you browse the navigation links, so it won’t fetch the first post for every page.
I added some html comments…

<div class=”post”>
<div class=”entry”>

<!–shows the first post only in the first page of posts–>

<?php if ( is_home() and !is_paged() ) : ?>
<?php query_posts(’showposts=1′); ?>
<?php while (have_posts()) : the_post(); ?>
<ul class=”archive”>
<li> <!–INSERT THE STYLE FOR THE FIRST POST–></li>
</ul>
<?php endwhile; ?>

<!–end of the first post: you can add here some advertising, Google adsense…like this–>

<!–shows other 9 posts with the same style–>

<?php query_posts(’offset=1&showposts=9&orderby=post_date&order=desc’); ?>
<?php while (have_posts()) : the_post(); ?>
<ul class=”archive”>
<li> <!–INSERT THE STYLE FOR THESE 9 POSTS–></li>
</ul>
<?php endwhile; ?>
<!–end of the last 9 posts of the first page only–>

<!–if it is not the first page: use this to style the older posts (from page two and on)–>
<?php else : ?>

<!–STANDARD LOOP–>
<?php  $page = (get_query_var(’paged’)) ? get_query_var(’paged’) : 1;
query_posts(”showposts=10&paged=$page”);  ?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<ul class=”archive”>
<li> <!–INSERT THE STYLE FOR THE STANDARD LOOP POSTS–></li>
</ul>
<?php endwhile; ?>
<?php endif; ?>
<?php endif; ?>
</div><!–end entry–>

<!–navigation links–>
<div class=”navigation”>
<div class=”alignleft”><?php next_posts_link(’&laquo; Older Entries’) ?></div>
<div class=”alignright”><?php previous_posts_link(’Newer Entries &raquo;’) ?></div>
</div>

</div><!– end post –>

Many thanks to Darren Hoyt

Popularity: 6% [?]

You can leave a response, or trackback from your own site.



Leave a Reply