0
0
Wordpressframework~5 mins

The Loop and query in Wordpress

Choose your learning style9 modes available
Introduction

The Loop is how WordPress shows posts on your site. It goes through posts one by one and displays them. Queries decide which posts to show.

When you want to show a list of blog posts on your homepage.
When you want to display posts from a specific category on a page.
When you want to customize which posts appear, like only showing recent posts.
When creating a custom page template that shows posts differently.
When you want to show search results or archive pages with posts.
Syntax
Wordpress
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
  <!-- Your post content here -->
<?php endwhile; else : ?>
  <!-- No posts found message -->
<?php endif; ?>

have_posts() checks if there are posts to show.

the_post() sets up each post's data inside the loop.

Examples
Basic loop showing the title and content of each post.
Wordpress
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
  <h2><?php the_title(); ?></h2>
  <div><?php the_content(); ?></div>
<?php endwhile; endif; ?>
Custom query to show 3 posts from the 'news' category.
Wordpress
<?php
$args = array('category_name' => 'news', 'posts_per_page' => 3);
$query = new WP_Query($args);
if ( $query->have_posts() ) :
  while ( $query->have_posts() ) : $query->the_post(); ?>
    <h3><?php the_title(); ?></h3>
  <?php endwhile;
  wp_reset_postdata();
endif;
?>
Shows a message if no posts are found.
Wordpress
<?php if ( ! have_posts() ) : ?>
  <p>No posts found. Try again later.</p>
<?php endif; ?>
Sample Program

This is a simple WordPress page template that uses The Loop to show the latest posts with their title, date, and excerpt. If no posts are found, it shows a friendly message.

Wordpress
<?php
/* Template Name: Simple Loop Example */
get_header();
?>
<main>
  <h1>Latest Posts</h1>
  <?php if ( have_posts() ) : ?>
    <?php while ( have_posts() ) : the_post(); ?>
      <article>
        <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
        <p>Published on <?php the_date(); ?></p>
        <div><?php the_excerpt(); ?></div>
      </article>
    <?php endwhile; ?>
  <?php else : ?>
    <p>Sorry, no posts matched your criteria.</p>
  <?php endif; ?>
</main>
<?php get_footer(); ?>
OutputSuccess
Important Notes

Always use wp_reset_postdata() after custom queries to avoid conflicts.

The Loop works with the main query by default, but you can create custom queries for special cases.

Use semantic HTML tags like <article> and <main> for better accessibility.

Summary

The Loop is how WordPress shows posts one by one.

Queries decide which posts The Loop will show.

You can customize The Loop with WP_Query for special post lists.