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 />';
endwhile;
echo json_encode(array("everything"=>$titles));
wp_reset_postdata();
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.
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: