Posted on

Finding posts by slugs of terms

I have a term who name is for, example, Great Blue Trojans. The slug is GBT.

I want to be able to search for ‘GBT’ and return all the posts with this term. When I search ‘Great Blue Trojans’ I get the hits. When I search GBT I do not.

Is this as expected? Is there anything I could do to change if it is?

By default Relevanssi does not index the slug.

Add this to your theme functions.php and rebuild the index, and you should be able to find posts by slug.

add_filter('relevanssi_content_to_index', 'rlv_term_slugs', 10, 2);
function rlv_term_slugs($content, $post) {
	$tags = get_the_terms($post->ID, TAXONOMY);
	if ($tags !== FALSE) {
		$tagstr = "";
		foreach ($tags as $tag) {
			if (is_object($tag)) {
				$content .= $tag->slug . ' ';
			}
		}
	}
}

Replace TAXONOMY with the name of the taxonomy of the terms you want to index – “post_tag” for tags, “category” for categories and so on.

Originally asked on WordPress.org.

  • Another Bob

    I’ve been trying to search for woocommerce product category slugs. Will this solution work?

    I’m pretty new to wordpress and I’m not a programmer so please forgive my ignorance 🙂
    In this solution what would I put in place of TAXONOMY?

    Thanks, Bob

    • See Product > Categories. That page has a list of product categories, and the Slug is listed for each category. Use that slug for the taxonomy name.

      • Another Bob

        I’m not sure I understand. I have hundreds of different product category slugs that I would like to be indexed for search. Would I have to repeat that function for each slug?
        Sorry to be annoying

        • You have hundreds of different categories you want indexed? If so, yes. If you have one category with hundreds of items in it, then you need this just once.

          • Another Bob

            OK, thank you. I’m trying to make a store to sell products for every team in college football. Each team and conference is a category with a slug. Many of the products can go for multiple teams and therefore into each team category. For example a green and white shirt with a generic logo can go for all the teams that use green and white. All the other green and white products (mugs, hats, etc) go into the team categories as well.

            Thanks for your time. I appreciate it