0

Is there a way to make a category that will show in all categories in WordPress?

For example, categories on my website are:

  • Cat A
  • Cat B
    • Cat B1
    • Cat B2
    • Cat B3

I want a post tagged in Category A to be shown also in Category B and its children. So when they check mywebsite.com/category/cat-b1 they will also find Cat A.

I do not really know how to code, but I always can follow steps.

1
0

You can do this by using the pre_get_posts filter, which allows you to change they query before it is executed. In this way you can add Cat A to any request for categories. Like this:

add_filter ('pre_get_posts', 'wpse380282_add_cat_a');
function wpse380282_add_cat_a ($query) {
  // do this only on the front end for the main query if it is a category archive
  if ( !is_admin() && $query->is_main_query() && is_category() ) {
    // get the ID for Cat A
    $cat_id = get_cat_ID ('Cat A');
    // get category of the query (returns an array of current categories)
    $cats = $query->get( 'cat' );
    // add Cat A to the array of current categories
    $cats[] = $cat_id;
    // set the category query to the expanded array
    $query->set( 'cat', $cats );
    }
  }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.