Posted on

Indexing image alt texts

Relevanssi by default ignores image alt texts (and other tag attributes). That’s often the right thing to do because alt texts aren’t visible to users. Finding a post with a search term that only appears in an alt text may confuse a user.

If your alt texts are well crafted, they may help search. It’s not hard to make Relevanssi index the alt texts. Add this function to your site:

add_filter( 'relevanssi_post_content', 'rlv_index_alt_text' );
function rlv_index_alt_text( $content ) {
    $content = preg_replace( '/<img .*?alt="(.*?)".*?>/is', ' \1 ', $content );
    return $content;
}

This function uses the relevanssi_post_content filter hook, which processes all post content before Relevanssi indexes it. All the HTML tags are still in the content – Relevanssi removes them later – so it is easy to make changes. It is easy for this function to find all IMG tags with an alt attribute and replace the whole tag with the contents of the alt attribute.

After you add this function, rebuild the index. Now the alt attributes are indexed!

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 *