Include images from pages in wp search.php results in default wp search

To include the attachment (media) post type in search results, use the following code snippet

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' );

Source

However, this does not take care of how the search results are displayed but that’s a discussion for another thread.

This should’ve worked, but if you want to add pages as well, then replace

$query->set( 'post_type', array( 'post', 'attachment' ) );

with

$query->set( 'post_type', array( 'post', 'page', 'attachment' ) );

Leave a Comment

tech