Performance: WP_Query class
This affects page load speed by controlling how many and which posts are fetched and rendered on a page.
$query = new WP_Query(array('posts_per_page' => 10, 'paged' => get_query_var('paged', 1)));
$query = new WP_Query(array('posts_per_page' => -1));
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Fetching all posts (-1 posts_per_page) | High (many nodes) | Multiple reflows | High paint cost | [X] Bad |
| Fetching limited posts with pagination | Low (few nodes) | Single reflow | Low paint cost | [OK] Good |
| Meta query without meta_query array | Medium | Single reflow | Medium paint cost | [!] OK |
| Meta query with meta_query array | Low | Single reflow | Low paint cost | [OK] Good |
WP_Query class in WordPress?WP_Query to get posts from category ID 5?new keyword and an array of arguments.'cat', not 'category' or 'category_id'.$query = new WP_Query(['cat' => 10]);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
echo get_the_title() . ', ';
}
} else {
echo 'No posts found';
}
wp_reset_postdata();have_posts() returns true, printing each post title followed by a comma.$query = new WP_Query(['post_type' => 'product']);
while ($query->have_posts()) {
the_post();
echo get_the_title();
}
wp_reset_postdata();$query->have_posts() but calls the_post() without the query object, which is incorrect.$query->the_post() to set up post data properly.'cat' => 3 to filter by category ID 3, not 'category_name' with a number string.tag__not_in argument expects an array of tag IDs, so we must get the ID using get_term_by().get_term_by('slug', 'featured', 'post_tag')->term_id inside the array correctly fetches the tag ID to exclude.Pass the test and this pattern moves unknown