WordPress Loop

This post is to sum­ma­rize and present the code snip­pets of the most Word­Press fun­da­men­tal: the loop.

1. Set up index.php
<?php get_header(); ?>
<div id="posts-container">
  // loop starts here
</div>
<?php get_sidebar(); ?>
<?php get_footer(); ?>
2. Sim­plest loop
if (have_posts()) :
  while (have_posts()) :
    the_post();
    the_content();
  endwhile;
endif;

Within the while loop:

  • Func­tion the_post() makes the cur­rent item in the posts col­lec­tion avail­able for use inside this iteration.
  • Tem­plate tag the_content() returns the post content.
3. Default loop
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
 
  <div <?php post_class(); ?> id="post-<?php the_ID(); ?>">
    <h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
    <?php the_content(); ?>
  </div>
 
<?php endwhile; ?>
 
<div class="navigation">
  <div class="next-posts"><?php next_posts_link(); ?></div>
  <div class="prev-posts"><?php previous_posts_link(); ?></div>
</div>
 
<?php else : ?>
	<h1>No posts found</h1>
 
<?php endif; ?>
4. Insert cus­tomized con­tent before the nth post
<?php if (have_posts()) : ?>
	<?php $count = 0; ?>
  <?php while (have_posts()) : the_post(); ?>
		<?php $count++; ?>
    <?php if ($count == n) : ?>
      //customized block of content here, might be Ad, video, image, etc.
      <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
      <?php the_content(); ?>
      <?php else : ?>
      	<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
      <?php the_content(); ?>
    <?php endif; ?>
	<?php endwhile; ?>
<?php endif; ?>
5. Remove spe­cific category(ies)
<?php query_posts('cat=-5, -7, -9'); ?>
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
	<?php the_content(); ?>
<?php endwhile; ?>

Above exam­ple removes the post(s) with cat­e­gories IDs 5, 7, and 9. Note the draw­backs of using query_post() such as alter­ing the main loop and pag­i­na­tion › ›

Ref­er­ences:
  • http://codex.wordpress.org/The_Loop
  • http://codex.wordpress.org/The_Loop_in_Action
  • http://wp.smashingmagazine.com/2009/06/10/10-useful-wordpress-loop-hacks
Updated 16 Oct 2011

[ Leave comments ]

You may use these HTML tags & attributes in your comment: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">