Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.