apply_filters( 'relevanssi_get_attachment_posts_query', string $query, int $limit, string $meta_join, string $meta_where )

Filters the SQL query that fetches posts with attachments.


(string) The SQL query that fetches attachment posts. Defaults to "SELECT DISTINCT(ID) FROM $wpdb->posts $meta_join WHERE post_type = 'attachment' AND post_status = 'inherit' AND post_mime_type LIKE %s $meta_where LIMIT %d", where %s is application/% and %d is the value of $limit.

(int) The number of posts to fetch. The default is 1.

(string) The SQL meta query JOIN clause.

(string) The SQL meta query WHERE clause.

More information

Relevanssi uses an SQL query to get the next unread attachment when attachments are read. The meta_query controls that: it looks for attachment posts where the _relevanssi_pdf_content custom field is empty, and where _relevanssi_pdf_error is either empty or has errors that mean it’s fine to try to reread the post (R_ERR02 for “privacy mode enabled”, cURL error 7 for “permission denied”, or cURL error 28 for “timeout”).

This query passes through this filter. The reason why you would want to modify this query is if you are reading attachment content from attachments that are not in the WordPress Media Library. Perhaps you want to change the post_type parameter to a custom post type – that would be a fairly common use case.

If you’re looking to index attachments that are in a custom post type document that has the post status publish instead of inherit, you could do the following:

add_filter( 'relevanssi_get_attachment_posts_query', 'rlv_attachment_to_document' );
function rlv_attachment_to_document( $query ) {
  return str_replace(
    "post_type = 'attachment' AND post_status = 'inherit'", 
    "post_type = 'document' AND post_status = 'publish'",

If you have a post type that doesn’t have a MIME type, you need this:

add_filter( 'relevanssi_get_attachment_posts_query', function( $query ) {
  return str_replace(
    "post_type = 'attachment' AND post_status = 'inherit' AND post_mime_type LIKE %s", 
    "post_type = 'documentat' AND post_status = 'publish' AND (post_mime_type LIKE %s OR post_mime_type = '')",
} );

You can also use relevanssi_get_attachment_posts_query_final where you don’t have to worry about the prepared statements like this.

You may also need to adjust the method of getting the attachment URL with relevanssi_get_attachment_url.

Actual use cases: