Skip to main contentSkip to footer

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.

Your account

Not logged in. Log in to see your license details.

Search

Popular Resources

Integrating Koko Analytics stats
It’s possible to integrate all kinds of external data to Relevanssi weights. Koko Analytics is a great analytics plugin. It…
EmbedPress autoembeds
EmbedPress has an auto-embed feature that tries to embed all URLs found in posts. This can cause problems with Relevanssi:…

Related Posts:

Comment Section:

3 Comments. Leave new

  • Pedro Cordeiro
    December 1, 2023 12:28 pm

    Recursivelly on infinite parents:

    add_filter( ‘relevanssi_content_to_index’, function( $content, $post ) {
    $categories = get_the_terms( $post->ID, ‘product_cat’ );
    if ( is_array( $categories ) ) {
    foreach ( $categories as $category ) {
    $category_id = $category->term_id;
    $i = 0;
    while ($category_id !== 0) {
    if($i !== 0) $category = get_term($category_id, ‘product_cat’);
    if ($category && !is_wp_error($category)) {
    $content .= ‘ ‘.$category->name.’ ‘;
    $category_id = $category->parent;
    } else {
    break;
    }
    $i++;
    }
    }
    }
    return $content;
    }, 10, 2 );

    Reply
  • Would you please also show us how to do it for grandparent categories? Thanks!

    Reply
    • Just repeat the step:

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

Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed