Posted on

Indexing term slugs

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. You can use the relevanssi_content_to_index filter hook to solve this.

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 ( false !== $tags ) {
		$tagstr = '';
		foreach ( $tags as $tag ) {
			if ( is_object( $tag ) ) {
				$content .= $tag->slug . ' ';
			}
		}
	}
  	return $content;
}

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.

7 comments Indexing term slugs

  1. 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

      1. 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

          1. 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

Leave a Reply

Are you a Relevanssi Premium customer looking for support? Please use the Premium support form.

Your email address will not be published. Required fields are marked *