How to Use WP_Query to Display Custom Post Type in WordPress (2024)

See the source image

Can wp_query be used to display custom post types? And how can do you it?

"How do I display a list of posts from a custom post type on my homepage?" you might wonder as a WordPress developer.

For something like a blog page, you might just want to show the custom post title and a link back to the custom post. Perhaps you want to display a variety of dynamic content, such as custom fields, images, and so on.

We're about to show you how to use the powerful WP Query class to fetch and output your posts on your website, and we'll show you how!

WP Query is a WordPress theming class that takes a number of parameters and requests and fetches posts based on those parameters.

The example below shows how to set a list of parameters, retrieve posts that match those parameters, and display the post's title and excerpt on the website. Take a look at the example below, which follows these steps.

  1. Create a variable with an array of parameters to pass to the WP Query class. The 'post type' parameter should be set to the slug of the custom post type we want to query. This is most likely the custom post type you've already created. If you haven't done so already, learn how to create custom post types in WordPress.
  2. Set the 'post status' parameter to 'published' to ensure that the requested posts are not in a 'draught' state. You could simply set this to 'draught' or any of the other post status parameters to get unpublished posts.
  3. The parameter 'posts per page' allows you to specify the number of posts you want to fetch and return.
  4. 'orderby' and 'order' are the last two parameters you should add. The 1st parameter, 'orderby,' orders the posts by title, while the 2nd, 'order,' orders all posts in ascending order by title or the 'orderby' parameter. Pass the parameters into the WP Query class and set the result to a variable once you've finished setting them up.

 

WP_Query Custom Post Type Examples

The First Example

/**

 * Setup query to show the ‘services’ post type with ‘8’ posts.

 * Output the title with an excerpt.

 */

    $args = array(  

        'post_type' => 'services',

        'post_status' => 'publish',

        'posts_per_page' => 8, 

        'orderby’ => 'title', 

        'order’ => 'ASC', 

    );

    $loop = new WP_Query( $args ); 

    while ( $loop->have_posts() ) : $loop->the_post(); 

        print the_title(); 

        the_excerpt(); 

    endwhile;

    wp_reset_postdata(); 

A More Advanced Example

When you look at our next example, you'll notice that it's a little more advanced. We've added a category parameter to only show posts in the 'home' category. You'll notice in the output that we've also included our loop to retrieve the featured image from the post and display it alongside the title and excerpt. This more advanced example demonstrates the power of the WP_Query.

/**

 * Setup query to show the ‘services’ post type with all posts filtered by 'home' category.

 * Output is linked title with featured image and excerpt.

 */

    $args = array(  

        'post_type' => 'services',

        'post_status' => 'publish',

        'posts_per_page' => -1, 

        'orderby' => 'title', 

        'order' => 'ASC',

        'cat' => 'home',

    );

    $loop = new WP_Query( $args ); 

    while ( $loop->have_posts() ) : $loop->the_post(); 

        $featured_img = wp_get_attachment_image_src( $post->ID );

        print the_title();

        if ( $feature_img ) {

           < img src="/print $featured_img['url']" width=”print $featured_img['width']" height="print $featured_img['height']" />

        }

        the_excerpt(); 

    endwhile;

    wp_reset_postdata(); 

Parameters

With WP_Query, you can customize the requested posts with a variety of parameters. We'll go over some of the most commonly used parameters below, but check out WordPress Codex's class reference on parameters for a more comprehensive list.

  • Cat - posts with a specific category id are filtered.
  • tag - A tag slug is used to filter posts.
  • tax_query - Filters posts based on taxonomic criteria.
  • s - A search keyword is used to filter posts.
  • Author - posts by a specific author are filtered.

Template Tags

There are many Template Tags you can use within your custom post type loop to dynamically output information. Other template tags you can use inside your loop include:

Now that you know the basics of WP Query and how to request and fetch your custom post type, you can use what you've learned to create your own custom post type templates with a variety of parameters and template tags to make it easy for visitors to see your custom posts.

IMH

Do you want a fast website?

Who am I kidding? Don't we all?

So why do so many of us struggle?

The biggest challenge is usually finding a fast, reliable hosting company.

We've all been through the nightmares - support take takes forever or doesn't resolve our problem always blaming something on your side... 

But the biggest bummer is that the website always feels slow.

At CollectiveRay we host with InMotion hosting and our website is stupid fast. We run on a custom stack of LightSpeed server setup on MariaDB with a PHP7.4 engine and fronted through Cloudflare. 

Combined with our front-end optimizations we reliably server 6000 users every single day, with peaks of 50+ simultaneous users. 

Want to get a fast setup like ours? Transfer your site for free to InMotion hosting and get our 50% OFF on current pricing.

Try InMotion Hosting with 50% OFF for CollectiveRay visitors in April 2024 ONLY!

InMotion hosting 50% OFF for CollectiveRay visitors

WP_Query Custom Post Type FAQs

WP query : What is it and how does it work?

WP Query only does one thing: it retrieves WordPress post bundles from the WordPress database. Before you can understand WP Query, you must first understand WordPress's basic engine: the Loop, which takes these bundles of fetched posts and processes them one by one into the contents of your site's pages.

What is the WP query class?

WordPress has a class called WP Query, it enables programmers to create custom queries and display posts based on various parameters. Developers have the ability to query the WordPress database directly.

How do I show the WP query results in WordPress?

The WordPress loop would be used to display the query's results. As an example: WP Query is a powerful tool with a number of parameters that can be used to create more advanced and complex queries. Using WP Query, you can make nested loops (a WordPress loop inside a loop).

About the Author
Shahzad Saeed
Shahzaad Saaed has been featured in a large number of authority websites including EasyDigitalDownloads, OptinMonster and WPBeginner where he is currently employed as a senior content writer. Shahzad is a WordPress expert, web designer and overall technology and design expert. He specializes in content marketing to help business grow their traffic through actionable and experience-backed articles, blogs and expert guides, all taken from his over 10 years of experience in the field.

One more thing... Did you know that people who share useful stuff like this post look AWESOME too? ;-)
Please leave a useful comment with your thoughts, then share this on your Facebook group(s) who would find this useful and let's reap the benefits together. Thank you for sharing and being nice!

Disclosure: This page may contain links to external sites for products which we love and wholeheartedly recommend. If you buy products we suggest, we may earn a referral fee. Such fees do not influence our recommendations and we do not accept payments for positive reviews.

Author(s) Featured On:  Inc Magazine Logo   Sitepoint logo   CSS Tricks logo    webdesignerdepot logo   WPMU DEV logo   and many more ...