Skip to content
OSULZER.AT
Code2 min read· updated March 9, 2022

WordPress Category: Show Additional Posts from Another Category

A solution to a fairly specific problem: how to show posts from a completely independent category in a WordPress category as well.

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

PHP Freelancer

Prefer to have it done for you?

Customizations, plugins, and integrations - cleanly implemented, €120/h plus VAT.

See the PHP freelancer

New project?

Contact.

Tell me briefly about your project - I'll get back to you personally.

Your data is used solely to handle your inquiry. More in the privacy policy.