Loop Through Custom Post Type With Custom Taxonomy In WordPress

Sayan Dey

Sayan Dey / January 13, 2023

1 min read––– 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.

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

- subscribers – View all issues