Want visitors to find your PDF documents through your site’s search? By default, WordPress excludes attachment pages from search results, which means PDFs uploaded to your Media Library are invisible to the built-in search function.
This guide shows how to add a small PHP snippet that tells WordPress to include attachment pages (and your embedded PDFs) in search results.
Adding the search inclusion code
Add the following PHP snippet to your site. It hooks into WordPress’s query builder and adds attachment to the list of post types searched, alongside standard posts.
function attachment_search( $query ) {
if ( $query->is_search ) {
$query->set( 'post_type', array( 'post', 'attachment' ) );
$query->set( 'post_status', array( 'publish', 'inherit' ) );
}
return $query;
}
add_filter( 'pre_get_posts', 'attachment_search' );
Code language: PHP (php)
The snippet modifies the main WordPress search query before it runs. Setting post_type to include both post and attachment tells WordPress to return attachment records alongside standard posts. Setting post_status to include inherit covers attachments, which use that status rather than publish.
You can add this code using one of the following methods:
Using WPCode (recommended): Install the free WPCode plugin, go to Code Snippets > Add Snippet, paste the code, and activate it.
Add to functions.php: Add the code to your active theme’s functions.php file.
Once active, WordPress includes attachment pages in search results. Visitors searching for terms that appear in your PDF file names or attachment page titles will see those pages in the results.
This snippet applies to the main site search query. If your theme uses a custom search implementation or a search plugin, results may vary. Test after adding the code to confirm attachment pages appear as expected.
Frequently Asked Questions
Below are some common questions about including attachment pages in search.
Will this affect search performance?
Including attachments expands what the search query returns, so on sites with very large media libraries there can be a minor impact. For most sites, the difference is not noticeable.
Can I limit results to PDFs only?
The snippet above includes all attachment types. To restrict results to PDFs only, a more targeted query modification is needed. That goes beyond standard plugin configuration and requires custom development.