WordPress.org

Forums

Relevanssi - A Better Search
[resolved] Search By Woocommerce Category And Show Child Products (2 posts)

  1. davidjs
    Member
    Posted 1 year ago #

    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/

  2. Mikko Saari
    Member
    Plugin Author

    Posted 1 year ago #

    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.

Topic Closed

This topic has been closed to new replies.

About this Plugin

  • Relevanssi - A Better Search
  • Frequently Asked Questions
  • Support Threads
  • Reviews

About this Topic

Tags