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;
}