wp_query() get_col error

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”

Read More

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.

Related posts

Leave a Reply

1 comment

  1. 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...