Associating a CPT with default taxonomies
written by: Jeff McNearAssociating a CPT with default taxonomies
There are arguments against having multiple post types share a common taxonomy – mainly since the back-end sorting interface will not work as completely as you may want it to. If more than one post type use a taxonomy you can really only sort the array of posts a single time before having to start over (since a second sort will give the user an “invalid post type” prompt). But there are cases when the front-end wants to see mixed results…
Just adding “categories” to the the “taxonomy” line like this isn’t enough
'taxonomies' => array( 'category', 'reviewed'),
Since the real point of a shared taxonomy is to show both post types in a category array you will need to explicitly allow it in your functions file like this:
//SOURCE: https://premium.wpmudev.org/blog/add-custom-post-types-to-tags-and-categories-in-wordpress/
function themeprefix_show_cpt_archives( $query ) {
if( is_category() || is_tag() && empty( $query->query_vars['suppress_filters'] ) ) {
$query->set( 'post_type', array(
'post', 'nav_menu_item', 'ratings_reviews'
));
return $query;
}
}
add_filter( 'pre_get_posts', 'themeprefix_show_cpt_archives' );
You will also want both post types to appear in search results by adding something like this in your functions file:
//SOURCE: https://thomasgriffin.com/how-to-include-custom-post-types-in-wordpress-search-results/
function tg_include_custom_post_types_in_search_results( $query ) {
if ( $query->is_main_query() && $query->is_search() && ! is_admin() ) {
$query->set( 'post_type', array( 'post', 'ratings_reviews' ) );
}
}
add_action( 'pre_get_posts', 'tg_include_custom_post_types_in_search_results' );
and if you have a query in a template, you will need to do something like this:
<?php
$loop = new WP_Query(
// again we need to make the custom post type inclusion explicit
array(
'post_type' => array('post','ratings_reviews'),
'category_name' => get_field('category_slug_name'),
)
);
while ( $loop->have_posts() ) : $loop->the_post();
// The content you want to loop goes in here:
?>