Combine Multiple Categories Into One URL Slug

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:

Read More
/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!

Related posts

Leave a Reply

2 comments

  1. 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');
    
  2. Wouldn’t WordPress’s built-in sub-categories functionality solve this problem?

     + fruit
      + bananas
      + apples
      + pears
    

    you would get all of fruit through

    /categories/fruit
    

    but also specific categories through

    /categories/fruit/bananas
    

    to add a sub-category, just choose fruit as the parent category for each child.