apply_filters( 'relevanssi_related_words', string $words, int $post_id )
This filter hook filters the source words for Related Posts for each post.
Parameters
$words
(string) A string of space-separated search terms for the post.
$post_id
(int) The post ID.
More information
When Relevanssi generates the Related Posts, Relevanssi uses the function relevanssi_related_generate_keywords()
to come up with a list of search terms from the post. The sources for these words depend on the Related Posts settings but can include post title, tags, categories and other taxonomies and the _relevanssi_related_keywords
custom field.
Relevanssi compiles these words into a list and returns them through this filter.
You can use this filter hook to modify the words. For example, I have a site where I use taxonomies a lot. Some of the terms are very common and not useful for Related Posts, while others are significant. I first remove the common words from the Related Posts source words to make the Related Posts more precise. I also remove dates because some posts have dates in the titles, and I don’t want that in Related Posts:
add_filter( 'relevanssi_related_words', function( $words ) { $common_words = array( 'adults', 'winners', 'families', ); $words = str_replace( $common_words, '', $words ); $words = preg_replace( '/\d+\.\d+\.\d+/', '', $words ); return $words; } );
On another site, I have Relevanssi generate the search terms from post titles as usual. I generate all the taxonomy terms manually with a function hooked on to this filter hook. I want to control how Relevanssi searches for those taxonomy terms: for some taxonomies, I want Relevanssi to wrap the terms in phrase quotes, and for some taxonomies, I want taxonomy targeting. See Using phrases in Related Posts for more details.