Custom post type queries let you get specific groups of content in WordPress. This helps you show only the posts you want, like products or events.
0
0
Custom post type queries in Wordpress
Introduction
You want to list all books if you have a 'book' post type.
You want to show only upcoming events from an 'event' post type.
You want to display portfolio items separately from blog posts.
You want to filter posts by a custom post type on a page.
You want to create a custom archive page for a special content type.
Syntax
Wordpress
$query = new WP_Query([ 'post_type' => 'your_post_type', 'posts_per_page' => 5, 'order' => 'ASC', 'orderby' => 'date', // other query parameters ]);
Replace 'your_post_type' with the slug of your custom post type.
WP_Query returns posts matching your criteria, which you can loop through.
Examples
Get the latest 5 posts from the 'book' custom post type.
Wordpress
$query = new WP_Query([ 'post_type' => 'book', 'posts_per_page' => 5 ]);
Get all 'event' posts ordered by date from oldest to newest.
Wordpress
$query = new WP_Query([ 'post_type' => 'event', 'orderby' => 'date', 'order' => 'ASC' ]);
Get posts from both 'book' and 'movie' post types, up to 10 posts.
Wordpress
$query = new WP_Query([ 'post_type' => ['book', 'movie'], 'posts_per_page' => 10 ]);
Sample Program
This code gets the 3 newest posts from the 'product' custom post type and prints their titles line by line. If no products exist, it shows a message.
Wordpress
<?php // Query 3 latest 'product' posts $query = new WP_Query([ 'post_type' => 'product', 'posts_per_page' => 3 ]); if ($query->have_posts()) { while ($query->have_posts()) { $query->the_post(); echo get_the_title() . "\n"; } } else { echo "No products found."; } wp_reset_postdata(); ?>
OutputSuccess
Important Notes
Always call wp_reset_postdata() after a custom query to restore global post data.
You can combine custom post type queries with other filters like taxonomy or meta queries.
Use pre_get_posts hook to modify main queries for custom post types if needed.
Summary
Custom post type queries help you get specific content types in WordPress.
Use WP_Query with the post_type parameter to fetch posts.
Loop through results and reset post data after to keep WordPress working smoothly.