# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Search](https://wpide.com/library/category/search/)
- Tags: search, media, pdf
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/search-include-documents/

## Code

```php
// 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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Include PDFs and Documents in Search Results" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
