Indexing attachment filenames

Relevanssi has been working nicely for the normal usecase. But how does one setup indexing of attachment files. When someone searches by filename or extension like pdf, there are no results. I have enabled ‘attachment’ at Relevanssi ‘Indexing options’ and still there are no results.

Relevanssi doesn’t index attachment file names. For attachments, Relevanssi indexes title and description.

However, adding the file name to Relevanssi index is simple. Just add this function to your theme functions.php and rebuild the index:

add_filter('relevanssi_content_to_index', 'rlv_add_filenames', 10, 2);
function rlv_add_filenames($content, $post) {
    if ($post->post_type == 'attachment') {
        $content .= " " . basename($post->guid);
    return $content;

Notice that by default Relevanssi replaces periods with spaces, so “sample.pdf” is indexed as “sample pdf”. That should not be a problem, as also in searching “sample.pdf” becomes “sample pdf”. However, if you are using OR search, this can lead to lots of useless results when searching for one pdf will match all pdfs.

Originally asked here.