Working with Custom Post Types in WordPress

We have discussed in detailed in the previous articles that how to register a custom post type in WordPress, In this article we explore that how you use them in your WordPress website. Generally your theme is not responsible to display posts on the front end of your site of WordPress. Thus, here it may not always be the case as certain custom post types may not need always to be publicly displayed of content. What function of your post type is it depend on it. It all depends on what the function of your post type is. In WordPress for display the custom post type data, The WP_Query custom Loop you can use. Keep in mind that WP_Query accepts a post_type parameter that is determines what type of content to Return the data.

All of your product entries in WordPress is return in the below example:

$args = array( ‘posts_per_page’ => ‘-1’, ‘post_type’ => ‘products’,);
$myProducts = new WP_Query( $args );
// The Loop
while ( $myProducts->have_posts() ) : $myProducts->the_post();
// Reset Post Data

Products is set by the the post_type parameter, When you registered the Products custom post type which is the $post_type parameter value used. Then update the custom Loop for return only the products in the Specials category:

$args = array(‘posts_per_page’ => ‘-1’, ‘post_type’ => ‘products’, ‘tax_query’ => array(
array(‘taxonomy’ => ‘category’, ‘field’ => ‘slug’, ‘terms’ => ‘specials’)));

$myProducts = new WP_Query( $args );

In WP_Query using the tax_query parameter, above custom Loop return only those poroduct post type which is assigned to the Specials category. So the after the same method apply you can use this for creating custom Loops with WP_Query, this for used to display your custom post type content. During the developing more complex websites in WordPress It’s easy to see the power custom post types bring to WordPress.