Posted on

How to index parent categories

Suppose you have a parent category with no products in it but a child category does. If you search by the parent category can relevanssi be set up to show the products in the child category? Cars > Wiper Blades. A search for cars shows wiper blade products.

By default this does not work, because Relevanssi doesn’t index parent categories for posts, just the category attached to the post. However, Relevanssi is about control, so this can be done using the relevanssi_content_to_index filter hook.

Add the following code to functions.php of your theme and re-index:

add_filter( 'relevanssi_content_to_index', 'rlv_parent_categories', 10, 2 );
function rlv_parent_categories( $content, $post ) {
	$categories = get_the_terms( $post->ID, 'category' );
	if ( is_array( $categories ) ) {
		foreach ( $categories as $category ) {
			if ( ! empty( $category->parent ) ) {
				$parent = get_term( $category->parent, 'category' );
				$content .= $parent->name;
	return $content;

If you’re interested in different taxonomy than ‘category’, just replace the two occurrances of ‘category’ with the name of the taxonomy you want (for example ‘product_cat’).

Originally asked here.

2 comments How to index parent categories

    1. Just repeat the step:

      $parent = get_term( $category->parent, 'category' );
      if ( ! empty( $parent->parent ) ) {
          $grandparent = get_term( $parent->parent, 'category' );
          $content .= $grandparent->name;

Leave a Reply

Are you a Relevanssi Premium customer looking for support? Please use the Premium support form.

Your email address will not be published. Required fields are marked *