• Hello,

    I’m trying to build a custom WP search page outside of a theme to integrate into my website. I’m having difficulty displaying the search results (on the same page as the search page). Here’s my code:

    <div>
        <form role="search" action="" method="get" id="searchform">
        <input type="text" name="s" placeholder="Search Blog Posts"/>
        <input type="submit" alt="Search" value="Search" />
      </form>
     </div>
    
    <?php echo get_search_query(); ?>
    
    <?php
    echo $_GET['s'];
    $args = array( 'posts_per_page' => 5, 'post_title' => $_GET['s'] );
    $loop = new WP_Query( $args );
    while ( $loop->have_posts() ) : $loop->the_post();
        the_title();
        the_content();
    endwhile;
    ?>

    Right now this displays all posts on my blog (regardless of if the title is $_GET[‘s’]. My followup question is how can I make it search for a keyword within the post title or post content rather than for the exact post title as I have now.

    Thank you so much!

Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    ‘post_title’ is not a valid WP_Query argument AFAIK, so it is ignored, thus you get all posts.

    The only WP_Query argument that results in keyword queries is the ‘s’ search argument. This queries the post content as well as the title. If you want to do a keyword search of only the title, you could do a regular ‘s’ query and then use the ‘posts_request’ filter to strip out the portion that queries post content.

    Probably preferable is to write your own mySQL query and use $wpdb methods to execute it. The SQL fragment that results in a keyword search of titles would look something like this:
    wp_posts.post_title LIKE '%keyword-here%'

Viewing 1 replies (of 1 total)

The topic ‘Custom Search Page’ is closed to new replies.