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.

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.