Loops

Common Loop

The below loop will display:

  • Post title as an <h2>
  • Post title is a Permalink to the post on its own page
  • The content of the post
  • Navigation to subsequent pages if the post spans multiple pages using <!–nextpage–> in the post (wp_link_pages )
  • A comments section
  1. <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <h2 id="post-<?php the_ID(); ?>"> <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent link to <?php the_title(); ?>"><?php the_title(); ?></a> </h2> <?php the_content(); ?> <?php wp_link_pages(); ?> <div> <?php comments_template(); ?> </div><!--commentblock--> <?php endwhile; ?> <div> <div><?php posts_nav_link(); ?></div> <div><!-- --></div> </div><!-- .navigation --> <?php endif; ?>

Custom  Loops

Specific Content

If, for example, you only want the title of a page to appear separately from content, use this loop:

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<h2 id="post-<?php the_ID(); ?>">
<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent link to <?php the_title(); ?>"><?php the_title(); ?></a>
</h2>
<?php endwhile; ?>
<?php endif; ?>

This example will list only the titles of the 4 most recent posts (as links):

<?php
 $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
 query_posts('posts_per_page=4'.'&paged=' . $paged);
 while ( have_posts() ) : the_post(); ?>
 <li>
 <a href="<?php the_permalink(); ?>"><?php the_title(); ?> | <?php the_date(); ?></a>
 </li>
 <?php endwhile; ?>

Specific Posts

The Loop can be limited to displaying only certain posts, for example those files in specific categories or with certain tags. The Query is added to the second line of the loop. For example, this query would only show excerpts from posts filed in the  category with ID 3:

<?php global $query_string;
          $posts = query_posts($query_string.'&cat=3');  ?>
           <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
           <?php the_excerpt();
endwhile;
endif; ?>

This is another way of displaying a specify post. This query would only show the post with ID 83:

<$id=83;
$post = get_post($id);
$content = apply_filters('the_content', $post->post_content);
echo $content;
?>

Note: Post IDs can be found by hovering over the page title on the Pages section of the WordPress dashboard. In Safari, with View>Status Bar showing, the URL of the post, including the post ID, will be displayed at the bottom of the browser window.
Multiple loops can be placed one one page either from a single or joined templates.In this way a single page can display content from different posts in different sections of the layout.
Full details on creating custom loops can be found within the WordPress Codex.