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’).
Would you please also show us how to do it for grandparent categories? Thanks!
Just repeat the step:
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 );