WP_Query for custom post type with a custom taxonomy

WP_Query for custom post type and custom taxonomy is the same as the normal WordPress queries to get posts.

In WP_Query you just need to pass ‘post_type‘ value (your custom post type slug) and if you have a custom taxonomy for that post_type then you also need to add tax_query in the query.

Custom post type with a custom taxonomy loop code #

// First lets set some arguments for the query:
$args = array(
    'post_type' => 'book',
    'posts_per_page' => 5,
    'tax_query' => array(
                array(
                     'taxonomy' => 'category',
                     'field' => 'slug',
                     'terms' => '$term_slug'
                )
           )
    // Several more arguments could go here. Last one without a comma.
);

// Query the posts
$query = new WP_Query($args);

// Loop 
echo '<table class="table table-hover">';
while ($query->have_posts()) : $query->the_post();
	echo '<tr>';
	echo '<td>' . get_the_title() . '</td>';
	
	echo '<td>' . get_post_meta(get_the_ID(), 'book_author', true) . '</td>';  // Within the loop, you can access custom fields like this
	echo '<td>' . get_post_meta(get_the_ID(), 'book_publisher', true) . '</td>';
	
	echo '<td>' . get_the_content() . '</td>';
        echo '</tr>';
endwhile;
</table>
// Reset Post Data
wp_reset_postdata();

Explanation:

In the above code, ‘book’ is the WordPress custom post type and in the tax_query¬†array field ‘category‘ is the name of the taxonomy in book post type.

Here I have used taxonomy ‘slug’ (name) to get the data, you can also use ‘term_id’, ‘name’ or ‘term_taxonomy_id’. The default value is ‘term_id’.

You can also create a custom post type custom taxonomy archive template.

If you want to place above code into custom taxonomy archive file then create a file called taxonomy-book_cat.php. This will be the archive template for your book_cat taxonomy.

 

Contact us on techinarea@gmail.com to get any WordPress solution and we will include your question in the WordPress solution category to help other developers.

Comments are closed, but trackbacks and pingbacks are open.