Today’s post deals with the solution to a fairly specific problem. If you want to show posts from a completely independent category in a WordPress category as well, you can use the code below. Of course, it would make more sense to put the post itself into both categories, but sometimes that is not easily possible or logical because of the way the site is structured.
You can activate the code below as a snippet through a suitable plugin, put it into the functions.php of your child theme, or move it into your own plugin. The latter should be the go-to solution.
/**
* Show posts from a separate category in the desired category
* @param $query
*/
function osulzer_top_news_category( $query ) {
if( $query->is_category() && isset($query->query['category_name']) && $query->query['category_name'] == 'slug-der-gewuenschten-kategorie' ) {
$query->set( 'category__in', [1, 2, 3] ); // IDs of the categories whose posts should also be shown here
$query->set( 'category_name', false ); // required so that not only posts from the current category are shown
$query->set( 'include_children', false ); // can be removed, defines whether posts from subcategories of the current category are shown as well
}
}
add_action( 'pre_get_posts', 'osulzer_top_news_category' ); // runs the code before the posts are queried from the database




