Include PDFs and Documents in Search Results
Lets the site search find PDF, Word, Excel and PowerPoint files from the Media Library by their title, caption and description, alongside posts and pages.
Opens WPIDE on
Code
// File types to include, as the start of their MIME type: PDF, Word, Excel and PowerPoint by default. Add 'image/' for images.
$wpide_search_file_types = array( 'application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument', 'application/vnd.ms-' );
add_action( 'pre_get_posts', function ( $query ) {
if ( is_admin() || ! $query->is_main_query() || ! $query->is_search() ) {
return;
}
$types = $query->get( 'post_type' );
if ( $types && 'any' !== $types ) {
$query->set( 'post_type', array_unique( array_merge( (array) $types, array( 'attachment' ) ) ) );
}
// Uploaded files have the status "inherit".
$query->set( 'post_status', array( 'publish', 'inherit' ) );
$query->set( 'wpide_search_files', true );
} );
add_filter( 'posts_where', function ( $where, $query ) use ( $wpide_search_file_types ) {
global $wpdb;
if ( ! $query->get( 'wpide_search_files' ) ) {
return $where;
}
$mimes = array();
foreach ( $wpide_search_file_types as $type ) {
$mimes[] = $wpdb->prepare( "{$wpdb->posts}.post_mime_type LIKE %s", $wpdb->esc_like( $type ) . '%' );
}
$mimes = $mimes ? '(' . implode( ' OR ', $mimes ) . ')' : '1=0';
// Files must have a matching type and be unattached or attached to published content; other "inherit" items (revisions) are left out.
$where .= " AND ( {$wpdb->posts}.post_status = 'publish' OR ( {$wpdb->posts}.post_type = 'attachment' AND {$mimes} AND ( {$wpdb->posts}.post_parent = 0 OR {$wpdb->posts}.post_parent IN ( SELECT ID FROM ( SELECT ID FROM {$wpdb->posts} WHERE post_status = 'publish' ) AS wpide_published ) ) ) )";
return $where;
}, 10, 2 );
Notes
Files attached to unpublished content stay hidden. Add 'image/' to the type list to include images too.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.