WordPress Loop a heart of the WordPress. It makes use PHP and HTML language. Loop extracts the data for each post from the WordPress database and inserts the appropriate information in place of each template tag. Let’s know how to work WordPress Loop.

The Basic Loop

<?php if(have_posts()) :
  while ( have_posts() ) : the_post();
    ... Display post content
  endwhile;
endif; ?>

Using the Loop

Open wordpress default theme index.php file. You see it loop that simple code here.
<?php get_header(); ?>
<?php if(have_posts()) :
  while ( have_posts() ) : the_post();
    ... Display post content
  endwhile;
endif; ?>
<?php get_footer(); ?>

Condition loop Use for 404 page

You can include a custom 404 “not found” message that will be displayed if no posts matching the specified criteria are available. The message must be placed between the end while and endif statements, as seen in examples code below.

<?php get_header(); ?>
<?php if(have_posts()) :
  while ( have_posts() ) : the_post();
    ... Display post content
  endwhile;
  else :
     _e( 'Sorry, no posts matched your criteria.', 'textdomain' );
endif; ?>
<?php get_footer(); ?>

Code for Blog Archive Page

WordPress provides a blog archive page if you are not making a category page you are all post listing on the archive page. You can see here the number of post fetching by Setting >> Reading >> Blog pages show at most. This page display post title, content summary and thumbnail image with his link.

<?php get_header(); ?>
<?php if(have_posts()) :
  while ( have_posts() ) : the_post();
    the_title();
    the_post_thumbnail();
    the_excerpt();
  endwhile;
  else :
     _e( 'Sorry, no posts matched your criteria.', 'textdomain' );
endif; ?>
<?php get_footer(); ?>

Code for Individual Post

As per WordPress functionality, WordPress provides an especially post page. Here displays the relevant information for that post just like post title, post thumbnail image, post content and it’s images.

<?php get_header(); ?>
<?php if(have_posts()) :
  while ( have_posts() ) : the_post();
    the_title();
    the_post_thumbnail();
    the_content();
  endwhile;
  else :
     _e( 'Sorry, no posts matched your criteria.', 'textdomain' );
endif; ?>
<?php get_footer(); ?>

Code for a Particluar Category

Display here any particluar category posts title, content summary and thumbnail image with his link.

<?php get_header(); ?>
<?php if(have_posts()) :
  while ( have_posts() ) : the_post();
    if ( in_category( 3 ) ) : ?>
    < div class="cat-three" >
    <?php else : ?>
    < div class="post" >
    <?php endif; ?>
    <?php the_title();
    the_post_thumbnail();
    the_excerpt();
  endwhile;
  else :
     _e( 'Sorry, no posts matched your criteria.', 'textdomain' );
endif; ?>
<?php get_footer(); ?>