How do I get my custom query to work with search results after the first page?

Before we begin, I must point out the following:

  • You’re using a file in your theme to send AJAX requests to, don’t do this, there are security implications. Instead, use the WP AJAX API, you’ll be able to remove half the code and make it work without having to change the URL everytime your site moves
  • You used query_posts to make your query, this is almost always a bad thing. If you need to query for posts, use get_posts or a WP_Query object. If you need to change what the main query does ( e.g. only show X on the homepage ) then use the pre_get_posts filter
  • You have a line with an if statement, a for loop, and an assignment, this is bad, imagine you got told there was an error on that line in your error log, how would you know which part caused the error?
  • You pass an offset to the AJAX call then ignore it
  • Use of $ with jQuery in no conflict mode, could cause issues and implies you’re bundling your own jquery rather than the one built into WordPress ( jQuery(document) not $(document) )

As for your problem, you made a query, but you specified:

query_posts(array(
    'paged' => $page,
    'post__not_in' => $last_twelve_ids
));

aka:

Show me all the posts on page X but not these posts: a,b,c,d,e,f, etc

Nowhere have you specified what the search term is, so how will it know? Code isn’t psychic, and there is no auto-magic here to figure out that you’re trying to search for something, it needs to be told.

To do this, lets look at the WP_Query codex page that lists all the possible parameters

Show posts based on a keyword search.

  • s (string) – Search keyword.

Which gives us:

$query = new WP_Query(
    's' => $search_term
    'paged' => $page,
    'post__not_in' => $last_twelve_ids
);
while ( $query->have_posts() ) {
    $query->the_post();
    // etc

But we didn’t pass along a search term in your AJAX call, so how does it know what to search for? We’ll need something like this to recieve it:

$search_term = (isset($_GET['searchterm'])) ? $_GET['searchterm'] : 0;

And in your AJAX call, you’ll need to change the javascript here:

data       : {pageNumber: pager, offset: 12, searchterm: searchterm },

You’ll need to assign searchterm a value in your javascript before the load call, how you do that though is dependent on your html, and you haven’t provided that.

After doing this, you will have what you needed, however you will still have these issues:

  • An insecure AJAX endpoint inside your theme ( use the WP AJAX API )
  • A hardcoded path to your website in your javascript ( again WP AJAX API will fix this )
  • PHP that doesn’t validate the inputs and could lead to an injection attack

Further Reading