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

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

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

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x