iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

The Loop

The Loop is the canonical pattern: WordPress runs a query, then your template iterates posts and renders each one. Inside the loop, template tags (the_title, the_content) operate on the “current” post.

Default + custom + WP_Query

EXAMPLE
<?php
// 1) The default loop — uses the main query for the URL being rendered
if (have_posts()) :
    while (have_posts()) : the_post();
        ?>
        <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
            <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
            <p class="meta">
                <?php echo esc_html(get_the_date()); ?> by <?php the_author(); ?>
            </p>
            <?php the_excerpt(); ?>
        </article>
        <?php
    endwhile;
    the_posts_pagination();
else :
    ?><p>No posts found.</p><?php
endif;
?>

<?php
// 2) Custom query — WP_Query for something OTHER than the main URL
$q = new WP_Query([
    'post_type'      => 'product',
    'posts_per_page' => 12,
    'tax_query' => [[
        'taxonomy' => 'product_cat',
        'field'    => 'slug',
        'terms'    => 'gadgets',
    ]],
    'meta_query' => [[
        'key'     => 'stock',
        'value'   => 0,
        'compare' => '>',
        'type'    => 'NUMERIC',
    ]],
    'orderby' => 'date',
    'order'   => 'DESC',
]);

if ($q->have_posts()) :
    while ($q->have_posts()) : $q->the_post();
        get_template_part('partials/product-card');
    endwhile;
    wp_reset_postdata();   // CRITICAL — restore the main query's post
else :
    echo '<p>No products.</p>';
endif;
?>

<?php
// 3) Functional alternative — get_posts (no global state)
$posts = get_posts([
    'post_type'      => 'product',
    'posts_per_page' => 5,
]);

foreach ($posts as $post) {
    setup_postdata($post);
    the_title('<h2>', '</h2>');
    the_excerpt();
}
wp_reset_postdata();
?>

Why it matters

Always wp_reset_postdata() after a custom WP_Query. Without it, every loop after yours sees YOUR last post as the “current” one — obscure bugs and broken templates follow.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
<?php if (have_posts()): while (have_posts()): the_post(); ?>
    <h2><?php the_title(); ?></h2>
    <div><?php the_content(); ?></div>
<?php endwhile; endif; ?>
Try it Yourself »

Exercise

Print the post title inside the loop.

<?php (); ?>

Test yourself

Q1. The Loop is WordPress' way to…
Q2. Inside the loop you typically call…
Q3. You start the loop with…

Discussion

Loading…