I'm trying to create an auto search jQuery function by using AJAX to send data to the database and back to the search field.

In my wordpress theme, I create a folder called "include" and in there I created a file called "autoSearch.php"

In that file I have my PHP code like so:

global $wpdb;

$searchQuery = mysql_escape_string($_POST['value']);

$mypostids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_title LIKE '$searchQuery' LIMIT 5");

$args = array('post__in='.$mypostids);

$res = new WP_Query($arg);  

$titles ="";

while ( $res->have_posts() ) : $res->the_post();
    $titles .= get_the_title().'<br />';

echo json_encode(array("everything"=>$titles));

However, I get the error: Fatal error: Call to a member function get_col() on a non-object.

I have no idea why that's happening. Thanks for the help in advance.

  • 1
    WP_Query takes an s parameter in it's argument that is the same thing that's used by the default search. Why not use that? – mrwweb Jul 30 '12 at 21:17
  • I have no idea what that even means. I don't usually use the WP_Query. Additionally, I'm new to wordpress so this has gotten me in a frenzy of confusion. – Majed Jul 30 '12 at 22:00
  • Whenever frenzy arrives, leave the computer immediately and return only when it leaves... ;) – brasofilo Jul 31 '12 at 7:28

UPDATE, Correct Answer: The core WordPress functions are inaccessible at time when using AJAX calls. The proper way to handle this is covered in "AJAX in Plugins" on the Codex.

Original answer that didn't solve the issue but might be interesting for others some day.

Here's an alternate way that avoids having to directly query the DB. You'd replace all of your code up to and including the $res = ... line:

// get search term
$search_query = mysql_escape_string($_POST['value']);
// args for get_posts
$my_post_args = array( 's' => $search_query, 'fields' => 'ids' );
// get array of post IDs (see "fields" argument above)
$my_post_ids = get_posts( $my_post_args );
// now WP_Query args
$res_args = array( 'post__in=' . $my_post_ids );
// make sure that the args parameter matches (it doesn't in your code snippet)
$res = new WP_Query( $res_args );
// etc...
  • Interesting, but now it also returns this error: Fatal error: Call to undefined function get_posts() – Majed Jul 30 '12 at 22:32
  • OK. Well I completely misdiagnosed that one. Sorry. I believe you want to read through "AJAX in Plugins" on the Codex. The snippet above should still work, but it doesn't address the problem. – mrwweb Jul 31 '12 at 0:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.