Add Multiple Post Type to Category Archive Page

WordPressPosted on

In WordPress, we can assign the default category taxonomy to multiple custom post types; this is an excellent way to avoid duplicate terms across multiple taxonomies.

At Pine, we use the category both for posts and snippets. One thing which we had to do is to add the snippet’s custom post type to the category listings. We did it the following way:

/**
 * Add snippets CPT to category archive page
 */
function pine_multiple_post_type_in_cateogry($query)
{
    if($query->is_main_query() && is_category()){
        $query->set('post_type', ['post', 'snippets']);
        return;
    }
}
add_action('pre_get_posts', 'pine_multiple_post_type_in_cateogry');

Using the pre_get_posts action, we can modify any query as we wish. Here we extended the queried post type list.

Need a web developer? Maybe we can help, get in touch!

Looking for web dev job?
You can check them on Jooble.

To see and write comments, you must allow the related (Disqus) cookies. For more information, please visit our privacy policy page.

Similar Posts

More content in WordPress category