Loop Through Custom Post Type With Custom Taxonomy In WordPress

Sayan Dey

Sayan Dey / January 13, 2023

1 min readNaN views

In WordPress, you can use the WP_Query class to loop through custom post type with custom taxonomy.

Here's an example of how you can use WP_Query to loop through a custom post type called "books" and a custom taxonomy called "book_category."

1

Use this `WP_Query` snippets in your theme files.

book-template.php

_20
$args = array(
_20
'post_type' => 'book',
_20
'post_status' => 'publish',
_20
'posts_per_page' => 3,
_20
'order' => 'ASC',
_20
'tax_query' => array(
_20
array(
_20
'taxonomy' => 'book_category',
_20
'terms' => 'fantasy',
_20
'field' => 'slug'
_20
)
_20
)
_20
);
_20
$loop = new WP_Query( $args );
_20
while ( $loop->have_posts() ) {
_20
$loop->the_post();
_20
}
_20
// Display the post content here
_20
endwhile;
_20
wp_reset_postdata();

This code will loop through all the "books" that have the "fantasy" book_category.

You can modify the "taxonomy" and "terms" fields to match your custom taxonomy and terms.

Conclusion

I hope this helps! Let me know if you have any questions on Guestbook. Subscribe to my weekly newsletter for more WordPress tutorials like this.

Subscribe to the newsletter

Get emails from me about web development, tech, and early access to new articles.

NaN subscribers – View all GitHub issues