WordPress.org

Ready to get started?Download WordPress

Forums

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

  1. davidjs
    Member
    Posted 2 months 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 2 months 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.

Reply

You must log in to post.

About this Plugin

About this Topic

Tags