Support » Plugin: Relevanssi - A Better Search » Search By Woocommerce Category And Show Child Products

  • Resolved davidjs

    (@davidjs)


    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.

    https://wordpress.org/plugins/relevanssi/

Viewing 1 replies (of 1 total)
  • Plugin Author Mikko Saari

    (@msaari)

    By default this does not work; posts only know their category, not a parent category.

    However, Relevanssi does give you total control over search results, so it can be done.

    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;
    }

    This function, added to your theme functions.php, will make posts searchable by the parent category, once you reindex the database. If you’re looking for another taxonomy, for example product category, just change ‘category’ to the name of the taxonomy.

    If you want to, it’s simple to change the code to account for grandparent categories as well.

Viewing 1 replies (of 1 total)
  • The topic ‘Search By Woocommerce Category And Show Child Products’ is closed to new replies.