Posted on

Controlling attachment types in index

Relevanssi lets you index attachments – not their contents, but the names and descriptions. But perhaps you only want to index a particular type of attachment? Relevanssi settings don’t have any control over that, it’s either all attachments or nothing.

It is possible to choose which kinds of attachments are indexed. It is done with the relevanssi_do_not_index filter hook, which lets you choose whether a particular post is indexed or not. You can use the attachment MIME type to see which kind of attachment it is and use that information to weed out unwanted attachments.

No images

To remove all image attachments from the index, add this code to your theme functions.php file and rebuild the index. It will weed out all attachments that have a MIME type that begins with “image”.

add_filter('relevanssi_do_not_index', 'rlv_no_image_attachments', 10, 2);
function rlv_no_image_attachments($block, $post_id) {
  $mime = get_post_mime_type($post_id);
  if (substr($mime, 0, 5) == "image") $block = true;
  return $block;

Only PDFs

This function will only index PDF attachments, and nothing else.

add_filter('relevanssi_do_not_index', 'rlv_only_pdfs', 10, 2);
function rlv_only_pdfs($block, $post_id) {
  $mime = get_post_mime_type($post_id);
  if (!empty($mime)) {
    $block = true;
    if (substr($mime, -3, 3) == "pdf") $block = false;
  return $block;

10 comments Controlling attachment types in index

  1. I tried this but it doesn’t seem to be working. Is there another way to remove them? They’re coming in first place in my search which is the last place I want them.

      1. Hi Mikko, just posts pages and downloads (from wpdownloadmanager). Also, is there a way to sort the results types, at the moment media is always on top and I want posts to be first, then downloads, then pages. (and no images).

  2. Actually… I think I might be talking about a different thing… I’m seeing images and such in the search box dropdown before I go to the whole page results… it’s in the search preview that I want to remove images.

    1. That isn’t probably coming from Relevanssi at all. As far as I can tell, the only Relevanssi-compatible search dropdown is SearchWP Live Ajax Search. If you’re using something else, it’s using the default WP search to get the results.

      1. oh… maybe that is something that came with my template. sorry to have bothered you. I’ll have to keep digging to see what’s going on.

    1. Eric, did you rebuild the index after adding the codes? If you didn’t, do that and that should solve the problem. These are indexing filters, and only take action when you are indexing posts.

      If that doesn’t help, then I would recommend debugging this, take a look at the values get_post_mime_type() is returning.

Leave a Reply

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