• Hi all – hoping to find a code solution for developing a custom search bar in WordPress that searches for both Posts/Pages but will ALSO search for media files such as PDFs and images. Basically I want the user to be able to type a search query into a custom search bar, and it will return ANYTHING that matches that query (and again it must be able to include pages, posts, AND media files). I’ve seen plenty of videos/tutorials on how to do this for pages/posts but have yet to find any code that deals with combining that with searching also for media files. Does anyone have/know of a proven/working code solution? I do not want to use a plug-in…..thanks all!

Viewing 2 replies - 1 through 2 (of 2 total)
  • Hi @dshstateca

    There are a few ways to build a custom search bar in WordPress that searches for both Posts/Pages and media files. One approach you can take is to use the WP_Query class to retrieve the search results. This class allows you to define the post types you want to include in the search, so you can set it to include both Posts and Pages and any custom post types you may have. You can also use the s parameter to specify the search term.

    Here’s an example of how you might use WP_Query to retrieve search results for Posts, Pages, and media files:

    $search_term = 'my search term';
    
    $query = new WP_Query( array(
        's'              => $search_term,
        'post_type'      => array( 'post', 'page', 'attachment' ),
        'post_status'    => 'publish',
        'posts_per_page' => -1,
    ) );
    
    if ( $query->have_posts() ) {
        while ( $query->have_posts() ) {
            $query->the_post();
            // Display the search results
        }
    } else {
        // No search results found
    }

    You can then use this query to loop through the search results and display them however you like.

    I hope this helps! Let me know if you have any questions or if you’d like further assistance.

    Thread Starter gm9090xyz

    (@dshstateca)

    Thanks Faisal – greatly appreciate the guidance, I’ll try it out this week!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Custom Search for PDFs images media files pages and posts’ is closed to new replies.