Posted on

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.

2 comments Indexing attachment filenames

  1. I have post type named: asset
    It has a custom field named: attachment-asset
    So, how to I index by filename of the files attached in the custom field?
    Is it possible in the free version?

    1. Use the relevanssi_content_to_index filter hook as described on the page. It works in the free version as well. How to exactly get the filename from your custom field depends on how the data is stored and so on, so I can’t comment on that.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.