1. Home
  2. Docs
  3. WordPress Developer
  4. WordPress Theme Development
  5. The Loop

The Loop

The Loop is the default mechanism WordPress uses for outputting posts through a theme’s template files. How many posts are retrieved is determined by the number of posts to show per page defined in the Reading settings. Within the Loop, WordPress retrieves each post to be displayed on the current page and formats it according to your theme’s instructions.

The Loop extracts the data for each post from the WordPress database and inserts the appropriate information in place of each template tag. Any HTML or PHP code in The Loop will be processed for each post.

Use Loop for

  • display post titles and excerpts on your blog’s homepage;
  • display the content and comments on a single post;
  • display the content on an individual page using template tags; and
  • display data from Custom Post Types and Custom Fields

Ex:

<?php if ( have_posts() ) : ?>

   <?php while ( have_posts() ) : the_post(); ?>

       … Display post content

   <?php endwhile; ?>

<?php endif; ?>

 

  • The have_posts() function checks whether there are any posts.
  • If there are posts, a while loop continues to execute as long as the condition in the parenthesis is logically true. As long as have_posts() continues to be true, the loop will continue.

The Loop should be placed in index.php, and in any other templates which are used to display post information.

the loop should always be placed after the call to get_header()

Ex :

<?php

   get_header();

   if ( have_posts() ) : while ( have_posts() ) : the_post();

       the_content();

   endwhile;

   else :

       _e( ‘Sorry, no posts matched your criteria.’, ‘textdomain’ );

   endif;

   get_sidebar();

   get_footer();

?>

The Loop can display a number of different elements for each post.

  • the_category() – the category or categories associated with the post or page being viewed
  • the_author() – the author of the post or page
  • the_content() – the main content for a post or page
  • the_excerpt() – the first 55 words of a post’s main content followed by an ellipsis (…) or read more link that goes to the full post. You may also use the “Excerpt” field of a post to customize the length of a particular excerpt.
  • the_meta() – the custom fields associated with the post or page
  • the_shortlink() – a link to the page or post using the url of the site and the ID of the post or page
  • the_tags() – the tag or tags associated with the post
  • the_title() – the title of the post or page
  • the_time() – the time or date for the post or page. This can be customized using standard php date function formatting.
Was this article helpful to you? Yes No

How can we help?