SponsoredHosinger Special Offer

WP WordPress Theme Development

Build classic and block WordPress themes from scratch: the template hierarchy, The Loop, the_title() and the_content(), template parts, menus, the Customizer, child themes and theme.json.

Custom Queries with WP_Query

WordPress Theme Development Lesson 21 of 30 ~4 min read

Overview

WP_Query is the class WordPress uses to fetch posts, and creating your own instance lets a template show an extra list — related posts, a featured carousel, the latest three projects — without disturbing the page's main query.

A secondary loop

<?php
$latest = new WP_Query(
    array(
        'post_type'           => 'post',
        'posts_per_page'      => 3,
        'ignore_sticky_posts' => true,
        'no_found_rows'       => true, // We are not paginating, so skip the count query.
    )
);
?>

<?php if ( $latest->have_posts() ) : ?>
    <section class="latest-posts">
        <h2><?php esc_html_e( 'Latest posts', 'gdc-starter' ); ?></h2>

        <?php while ( $latest->have_posts() ) : $latest->the_post(); ?>
            <?php get_template_part( 'template-parts/content', 'card' ); ?>
        <?php endwhile; ?>
    </section>
<?php endif; ?>

<?php wp_reset_postdata(); ?>

Note $latest->have_posts() and $latest->the_post() — you call them on your object, not the bare functions that read the main query.

Why wp_reset_postdata() is essential

$latest->the_post() overwrites the global $post. After your loop, every template tag would still describe the last post from your custom list. wp_reset_postdata() restores the global $post to the main query's current post. Leave it out and the comments below your related-posts box belong to the wrong post.

The arguments you will use most

ArgumentExampleMeaning
post_type'book' or array( 'post', 'page' )What to fetch
posts_per_page6 (-1 for all — avoid on large sites)How many
post__not_inarray( get_the_ID() )Exclude posts
category_name'news'By category slug
tax_querySee belowBy any taxonomy
meta_querySee belowBy custom field
orderby / order'date', 'title', 'rand' / 'DESC'Sorting
no_found_rowstrueSkip counting total rows — faster when not paginating

Related posts by shared category

<?php
$categories = wp_get_post_categories( get_the_ID() );

if ( $categories ) {
    $related = new WP_Query(
        array(
            'category__in'        => $categories,
            'post__not_in'        => array( get_the_ID() ),
            'posts_per_page'      => 3,
            'ignore_sticky_posts' => true,
            'no_found_rows'       => true,
        )
    );

    if ( $related->have_posts() ) {
        echo '<aside class="related"><h2>' . esc_html__( 'Related posts', 'gdc-starter' ) . '</h2>';
        while ( $related->have_posts() ) {
            $related->the_post();
            get_template_part( 'template-parts/content', 'card' );
        }
        echo '</aside>';
    }

    wp_reset_postdata();
}

Querying by taxonomy and custom field

<?php
$fantasy_bestsellers = new WP_Query(
    array(
        'post_type'      => 'book',
        'posts_per_page' => 8,
        'tax_query'      => array(
            array(
                'taxonomy' => 'genre',
                'field'    => 'slug',
                'terms'    => 'fantasy',
            ),
        ),
        'meta_query'     => array(
            array(
                'key'     => '_gdc_bestseller',
                'value'   => '1',
                'compare' => '=',
            ),
        ),
    )
);
Watch out: meta_query searches an unindexed column and gets slow on large sites. For data you filter by often, a taxonomy is usually the faster and cleaner choice.

When not to use WP_Query

You want toUse
Change the posts on the main page (count, order, type)pre_get_posts — never a new query in the template
A simple array of posts, no Loop neededget_posts() — a thin wrapper that returns an array
Replace the main queryNothing. Never use query_posts().

Practice

  • Add a "Latest posts" section to front-page.php with no_found_rows.
  • Add related posts to single.php, excluding the current post.
  • Remove wp_reset_postdata(), reload a post with comments, and see the comments area break — then put it back.
Create a free account to save which lessons you've finished. Save my progress