Posted on

Polylang attachment searching

If Polylang is in use and you haven’t enabled “Media translation“, your attachment files won’t have a language. That’s fine, except when Relevanssi searches fail to find your attachment because they’re looking for posts in a specific language.

Suppose you want to include attachments in Polylang searches. In that case, you can either enable “Media translate” so that your media files have a language, or you can use this code in your theme functions.php to always include attachments in the results:

add_filter(
  'relevanssi_where',
  function( $query ) {
    global $wpdb;
    
    $query  = str_replace( 'AND relevanssi.doc', 'AND ( relevanssi.doc', $query );
    $query .= ' OR relevanssi.doc IN ( SELECT DISTINCT(ID) FROM ' . $wpdb->posts . ' WHERE post_type = "attachment" ))';

    return $query;
  }
);

This function hooks onto the relevanssi_where filter hook to modify the Polylang taxonomy query so that the search always includes the attachments. This only works if the query uses no other query variables except the Polylang language query. The results may be unexpected if there are other query filters applied.

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 *