WP Query
WP_Query
is a powerful class in WordPress used to query and retrieve posts (or any custom post types) from the database. It allows developers to build custom loops beyond the default one used by WordPress.
What Does It Do?
- Fetches posts based on specific criteria (category, tag, post type, date, custom fields, etc.)
- Allows full control over what content is displayed, how many items, what order, and more
- Often used to replace or extend the default WordPress Loop
Basic Example
$args = [
'post_type' => 'post',
'posts_per_page' => 5,
];
$query = new WP_Query($args);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
the_title('<h2>', '</h2>');
the_excerpt();
}
wp_reset_postdata();
}
Common WP Query Parameters
Parameter | Description |
---|---|
post_type | 'post' , 'page' , 'your_cpt' , etc. |
posts_per_page | Number of posts to show |
category_name | Filter by category slug |
orderby , order | Sorting (e.g., date , title , ASC ) |
meta_query | Query by custom fields (ACF, etc.) |
tax_query | Filter by taxonomy terms |
paged | Support for pagination |
date_query | Filter by date range |
When to Use WP_Query
- Displaying custom post types like testimonials or events
- Building custom archive or filtered pages
- Creating sliders, carousels, or widgets with specific content
- Replacing the default loop in a theme
Always Reset Post Data
When using WP_Query
outside of the main loop, remember to call:
wp_reset_postdata();
This ensures that global post data is not altered for the rest of the page.
When Not to Use
- Inside main loop: use
have_posts()
andthe_post()
instead - For simple cases: consider helper functions like
get_posts()
orquery_posts()
(althoughquery_posts()
is discouraged)
Feature | Description |
---|---|
Purpose | Fetch and loop through custom content |
Use case | Full control over queried post data |
Best practice | Always reset post data after usage |
Related to | The Loop, get_posts() , query_posts() |