0
0
WordpressHow-ToBeginner · 3 min read

How to Query Custom Post Type in WordPress Easily

To query a custom post type in WordPress, use the WP_Query class with the post_type parameter set to your custom post type's name. This lets you fetch posts of that type easily within your theme or plugin.
📐

Syntax

The basic syntax to query a custom post type uses the WP_Query class with an array of arguments. The key argument is post_type, which specifies the custom post type slug.

  • post_type: The slug of your custom post type (string or array).
  • posts_per_page: Number of posts to retrieve.
  • order: Sorting order, e.g., 'ASC' or 'DESC'.
  • orderby: Field to sort by, e.g., 'date', 'title'.
php
$args = [
    'post_type' => 'your_custom_post_type',
    'posts_per_page' => 10,
    'order' => 'DESC',
    'orderby' => 'date'
];
$query = new WP_Query($args);
💻

Example

This example shows how to query and display the titles of the latest 5 posts from a custom post type called book. It loops through the results and prints each post title inside an unordered list.

php
<?php
$args = [
    'post_type' => 'book',
    'posts_per_page' => 5,
    'order' => 'DESC',
    'orderby' => 'date'
];
$query = new WP_Query($args);

if ($query->have_posts()) {
    echo '<ul>';
    while ($query->have_posts()) {
        $query->the_post();
        echo '<li>' . get_the_title() . '</li>';
    }
    echo '</ul>';
} else {
    echo 'No books found.';
}
wp_reset_postdata();
?>
Output
<ul><li>Book Title 1</li><li>Book Title 2</li><li>Book Title 3</li><li>Book Title 4</li><li>Book Title 5</li></ul>
⚠️

Common Pitfalls

Common mistakes when querying custom post types include:

  • Not setting the post_type parameter, which defaults to 'post' and returns standard posts only.
  • Forgetting to call wp_reset_postdata() after the loop, which can break other queries on the page.
  • Using the wrong custom post type slug (it must match exactly what was registered).
  • Not checking if the query has posts before looping, which can cause errors.
php
<?php
// Wrong: Missing post_type, returns default posts
$query = new WP_Query(['posts_per_page' => 5]);

// Right: Specify custom post type
$query = new WP_Query(['post_type' => 'book', 'posts_per_page' => 5]);

// Always reset post data after custom loop
wp_reset_postdata();
📊

Quick Reference

ParameterDescriptionExample Value
post_typeSlug of the custom post type to query'book'
posts_per_pageNumber of posts to retrieve5
orderSort order'ASC' or 'DESC'
orderbyField to sort by'date', 'title'
pagedPage number for pagination2

Key Takeaways

Use WP_Query with the post_type parameter to query custom post types.
Always check if the query has posts before looping through results.
Call wp_reset_postdata() after your custom loop to avoid conflicts.
Ensure the post_type slug matches exactly the registered custom post type.
You can customize query parameters like posts_per_page, order, and orderby.