TechBuzzPro

WP_Query in WordPress: Examples & Pagination

· 5 min read · Apps & Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

WP_Query is the WordPress class that lets you create custom loops to display posts, pages, and custom post types with precise control. This guide shows you how to use WP_Query with practical examples and how to add pagination so your custom loops don't break across multiple pages. You'll need a basic understanding of PHP and WordPress theme development, plus a code editor and a child theme or a custom plugin to place your code safely.

What You'll Need

  • A WordPress site (local or live) with theme files you can edit.
  • A code editor like VS Code or Sublime Text.
  • Basic knowledge of PHP, HTML, and CSS.
  • FTP access or a file manager in your hosting panel to upload files.
  • A child theme (recommended) so your changes aren't lost on theme updates.

Step-by-Step

  1. Create a custom query. Start with a simple WP_Query instance. The basic structure is:
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => 5,
    );
    $custom_query = new WP_Query( $args );
    This fetches the 5 most recent posts. You'll place this inside a template file, typically in a page template or a custom loop area.
  2. Set up the loop. Use have_posts() and the_post() to iterate through the results, just like the default loop:
    if ( $custom_query->have_posts() ) :
        while ( $custom_query->have_posts() ) : $custom_query->the_post();
            // Display post title, content, etc.
            the_title();
            the_excerpt();
        endwhile;
        wp_reset_postdata(); // Important: restore global $post
    endif;
    Always call wp_reset_postdata() after your custom loop to avoid conflicts with the main query.
  3. Filter by category or tag. Add a 'category_name' (slug) or 'tag' parameter to narrow results:
    $args = array(
        'category_name' => 'news',
        'posts_per_page' => 10,
    );
    For a tag, use 'tag' => 'featured'. You can also use 'cat' with a numeric ID.
  4. Query custom post types. Set 'post_type' to your custom post type slug, e.g., 'portfolio' or 'product'. You can also query multiple types with an array: 'post_type' => array( 'post', 'page', 'portfolio' ).
  5. Add meta key filtering. To show posts with a specific custom field, use 'meta_key' and 'meta_value':
    $args = array(
        'meta_key' => 'featured',
        'meta_value' => 'yes',
    );
    For more complex meta queries, use 'meta_query' with arrays.
  6. Order results. Use 'orderby' and 'order' to sort. For example, 'orderby' => 'date', 'order' => 'ASC' for oldest first, or 'orderby' => 'title' for alphabetical.
  7. Add pagination. The key is to pass the current page number to WP_Query using 'paged'. Get the current page with get_query_var( 'paged' ) or get_query_var( 'page' ) for static front pages. Then display pagination links with paginate_links().
    $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
    $args = array(
        'paged' => $paged,
        'posts_per_page' => 5,
    );
    $custom_query = new WP_Query( $args );
    // ... loop ...
    // Pagination:
    echo paginate_links( array(
        'total' => $custom_query->max_num_pages,
        'current' => $paged,
    ) );
    This creates numbered page links that work with your custom query.
  8. Use a custom page template. For a dedicated page, create a file like page-custom.php in your child theme, add a template header, and place your WP_Query code there. Then assign that template to a page in the admin.
  9. Reset the query. After the loop and pagination, always call wp_reset_postdata() to restore the original post data. This prevents issues with other loops on the same page.

Common Mistakes

  • Forgetting wp_reset_postdata() – This can cause the main loop to show wrong content or break other widgets.
  • Not setting 'paged' – Without it, pagination will always show the first page of results.
  • Using query_posts() – This function modifies the main query and is strongly discouraged. Always use WP_Query.
  • Ignoring the main query – If you're trying to alter the main loop on archive pages, use pre_get_posts instead of creating a new query.
  • Hardcoding page numbers – Don't use get_query_var( 'page' ) on archive pages; use 'paged'.

Tips

  • Use 'no_found_rows' => true when you don't need pagination to speed up the query.
  • For complex queries, use 'fields' => 'ids' to only fetch post IDs, then run a second query if needed.
  • Cache your query results with transients if you run heavy queries on high-traffic sites.
  • Always test your custom loops on a staging site first.
  • Use WP_Query in a widget or shortcode to make it reusable.

Troubleshooting

  • Pagination shows 404 or repeats content – Make sure you're using 'paged' and that your template is correctly set up. Check that your permalinks are flushed (Settings > Permalinks > Save Changes).
  • Custom loop doesn't appear – Verify that your post type exists and that you have posts. Check for PHP errors in your debug.log.
  • Main loop breaks after custom query – You likely forgot wp_reset_postdata(). Add it immediately after the custom loop.
  • Query is too slow – Add 'no_found_rows' if you don't need pagination, or consider using WP_Query with more specific arguments.
  • Pagination links don't show – Ensure you're passing 'total' and 'current' to paginate_links(), and that max_num_pages is greater than 1.

Frequently Asked Questions

What is the difference between WP_Query and query_posts()?

query_posts() replaces the main query and is inefficient; WP_Query creates a separate instance without altering the main loop, making it safer and more flexible.

How do I display pagination for a custom WP_Query?

Set the 'paged' argument to the current page number (from get_query_var('paged')), then use paginate_links() with the 'total' parameter set to $custom_query->max_num_pages.

Can I use WP_Query in a widget?

Yes, you can instantiate WP_Query inside a widget's widget() method, but remember to call wp_reset_postdata() after the loop.

How do I exclude posts from a WP_Query?

Use the 'post__not_in' parameter with an array of post IDs, e.g., 'post__not_in' => array( 12, 34 ).

Why is my WP_Query not respecting the 'posts_per_page' setting?

Check if your theme or a plugin is filtering pre_get_posts and overriding it. Also ensure you're not using 'posts_per_page' => -1 which shows all posts.

How do I get the total number of posts from a WP_Query?

Use $custom_query->found_posts to get the total count, and $custom_query->max_num_pages for the number of pages.