Not sure why this isn't working... my action is being passed and the right function is firing from my ajax, but the callback isn't receiving my query parameter.

My ajax (using bloodhound.js running from the administrative screens, so no need to localize):

new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
  url: ajaxurl,
  prepare: function(query,settings){
    settings.url = settings.url + '?query=' + query + '&action=' + 'find_posts'
    return settings;

If you're not familiar with Bloodhound, the query it renders looks like this:


Here fdsafpasdjflkdsajkfg is just the search string I typed in (in frustration 😢). So I know it is sending the correct query strings, and I also know because the error I get stems from the right action being fired.

My error is

PHP Fatal error: Call to a member function esc_like() on null

It stems from this:

add_action( 'wp_ajax_find_posts', 'find_posts' );

function find_posts(){
$query = $_GET['query'];
$value = '%'.$wpdb->esc_like($query).'%'; //ERROR HERE
$sql = $wpdb->prepare("SELECT ID, post_title 
        FROM {$wpdb->prefix}posts
        WHERE post_title LIKE %s
        ORDERBY BY ID", $value);
    $posts = $wpdb->get_results($sql);
    return json_encode($posts);

So the question is, why is $_GET['query']; resolving to null when it is in my query string?


Add global $wpdb; in function find_posts(), before you use $wpdb;

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.