Performance: Custom post type queries
This affects page load speed by controlling how many database queries run and how much data is fetched for custom post types.
<?php $paged = get_query_var('paged') ?: 1; $query = new WP_Query(array('post_type' => 'product', 'posts_per_page' => 10, 'paged' => $paged)); if ($query->have_posts()) { while ($query->have_posts()) { $query->the_post(); the_title(); } } wp_reset_postdata(); ?>
<?php $posts = get_posts(array('post_type' => 'product')); foreach ($posts as $post) { setup_postdata($post); the_title(); } wp_reset_postdata(); ?>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Fetching all posts without limits | N/A (server-side) | N/A | Blocks initial paint due to slow HTML generation | [X] Bad |
| Paginated query with limits | N/A (server-side) | N/A | Faster HTML generation enables quicker paint | [OK] Good |
| Query without caching | N/A (server-side) | N/A | Slower server response delays paint | [!] OK |
| Query with caching | N/A (server-side) | N/A | Fast server response improves paint timing | [OK] Good |
post_type in a WP_Query in WordPress?post_type parameter in WP_Query specifies which type of posts to fetch, such as posts, pages, or custom types.post_typeWP_Query?new WP_Query(array('post_type' => 'product')) with an associative array and the correct key post_type.new keyword, and D misspells post_type. $query = new WP_Query(array('post_type' => 'event'));
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
echo get_the_title() . ', ';
}
}
wp_reset_postdata();have_posts() returns true, iterating over all posts of type 'event'.get_the_title() prints each post's title followed by a comma, so all 3 titles appear separated by commas. $args = array('post_type' => 'book');
$query = WP_Query($args);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
the_title();
}
}
wp_reset_postdata();new keyword. The code misses new before WP_Query($args).wp_reset_postdata() is present, and the_title() is valid inside the loop.WP_Query argument array correctly achieves this?date_query parameter with an array specifying the year.date_query with year 2023. { 'post_type' => 'movie', 'year' => 2023 } uses an invalid 'year' key. { 'post_type' => 'movie', 'meta_key' => 'year', 'meta_value' => 2023 } filters by meta fields, not post date. { 'post_type' => 'movie', 'post_status' => '2023' } misuses post_status.Pass the test and this pattern moves unknown