I have a WordPress website with 20+ categories. To make it easier to navigate I want to decrease the categories, but at the same time keep the original categories. In other words I want to be able to query multiple categories with a category group or a virtual slug.
Example categories:
/category/apples/
/category/pears/
/category/bananas/
I want to be able to query all three of them with a unique url slug:
/category/fruit/
But like I said, it should still be possible to go to i.e. /category/bananas/
I know it’s possible to query multiple categories the way I want to using /category/apples,bananas,pears/ but it’s not a elegant solution.
Is it possible to do this virtual grouping with a plugin or even using a rewrite?
Tips and recommendations are greatly appreciated!
2 Answers
You could override your query with pre_get_posts
in functions.php
:
function add_all_fruits_to_category($query) {
$catnames = $query->get('category_name');
if ($catnames == 'fruits') {
$query->set('category_name', $catnames . ',bananas,apples,pears');
}
}
add_action('pre_get_posts', 'add_all_fruits_to_category');