WP_Query in WordPress: Examples & Pagination
In this article
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
- Create a custom query. Start with a simple WP_Query instance. The basic structure is:
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.$args = array( 'post_type' => 'post', 'posts_per_page' => 5, ); $custom_query = new WP_Query( $args ); - Set up the loop. Use
have_posts()andthe_post()to iterate through the results, just like the default loop:
Always callif ( $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;wp_reset_postdata()after your custom loop to avoid conflicts with the main query. - Filter by category or tag. Add a
'category_name'(slug) or'tag'parameter to narrow results:
For a tag, use$args = array( 'category_name' => 'news', 'posts_per_page' => 10, );'tag' => 'featured'. You can also use'cat'with a numeric ID. - 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' ). - Add meta key filtering. To show posts with a specific custom field, use
'meta_key'and'meta_value':
For more complex meta queries, use$args = array( 'meta_key' => 'featured', 'meta_value' => 'yes', );'meta_query'with arrays. - Order results. Use
'orderby'and'order'to sort. For example,'orderby' => 'date', 'order' => 'ASC'for oldest first, or'orderby' => 'title'for alphabetical. - Add pagination. The key is to pass the current page number to WP_Query using
'paged'. Get the current page withget_query_var( 'paged' )orget_query_var( 'page' )for static front pages. Then display pagination links withpaginate_links().
This creates numbered page links that work with your custom query.$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, ) ); - Use a custom page template. For a dedicated page, create a file like
page-custom.phpin your child theme, add a template header, and place your WP_Query code there. Then assign that template to a page in the admin. - 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 useWP_Query. - Ignoring the main query – If you're trying to alter the main loop on archive pages, use
pre_get_postsinstead 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' => truewhen 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_Queryin 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 usingWP_Querywith more specific arguments. - Pagination links don't show – Ensure you're passing
'total'and'current'topaginate_links(), and thatmax_num_pagesis 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.