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

The question:

Is there a way to include page images in wp search? Like I want to search through my sites images on pages not in posts by caption/alt text and display them in the results page as thumbnails.

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment