Custom WordPress Search Not Consistent with Results

I’ve set up a custom search to use the s GET variable on a URL. I want it to fetch certain results but I’ve come across an odd problem. First, here’s my code:

$search_term = $_GET['s'];

if($search_term!=''){
    $s = new WP_Query(array('s' => $search_term));
    $search_array = array();

    if($s->have_posts()){
        while($s->have_posts()){
            $s->the_post();

            $title = get_the_title();
            $permalink = get_permalink();
            $search_identifier = $title.$permalink;

            array_push($search_array,$search_identifier);
        }
    }
}

Essentially, I’m creating an array of unique values for each post because I need to use them for a function immediately after that.

Read More

I have a post titled ‘Kitchen Assistant.’ When I search ‘kitchen’, it shows up. When I search ‘assistant’ it does not show up.

I have other posts with the word ‘assistant’ in the title and content and those show up when I search ‘assistant’. I’m curious as to why it would show up with one search term and not the other?

I’ve used var_dump($s) and the post is in the dump when I search ‘assistant’ but not when I search ‘kitchen.’

Any help would be greatly appreciated. Thanks!

Related posts

Leave a Reply

2 comments

  1. Try this.

    $search_term = $_GET['s'];
    if(!empty($search_term)){
    
        $args = array(
            'post_type' => 'post',
            'meta_query' => array(
                'key' => 'title',
                'value' => $search_term,
                'compare' => 'LIKE'
            )
        );
    
        $s = new WP_Query($args);
        $search_array = array();
    
        if($s->have_posts()){
            while($s->have_posts()){
                $s->the_post();
    
                $title = get_the_title();
                $permalink = get_permalink();
                $search_identifier = $title.$permalink;
    
                array_push($search_array,$search_identifier);
            }
        }
    
    }
    
  2. I figured out the answer to my own question (finally!). I’m using the NineToFive template and I guess by default there’s a limit on the number of search results that’s returned (I’m not sure if that’s a WordPress default; maybe someone can clarify that).

    I changed my query to this:

    $s = new WP_Query(array('s' => $search_term, 'posts_per_page' => -1));
    

    To not put a limit on the search results and that changed it. I needed to find every possible search term on page 1 in order to cross reference it with the location but it was ‘paginating’ the search results in search query end of it.

    Thanks for the help!