I'm trying to get_results() in my widget's front end, this is my current code:

public function widget( $args, $instance ) {
    echo $args['before_widget'];
    if($children = $wpdb->get_results( "SELECT ID FROM $wpdb->posts" ))
         echo "working";
    echo $args['after_widget'];

However I'm getting error "Fatal error: Call to a member function get_results() on a non-object".

I need to access the database to create a menu with the page children. What's am I doing wrong?


2 Answers 2


It seems that you can't access to it. Please try add global $wpdb; to your function.


For reference, in WordPress Codex you will find:

WordPress provides a global variable, $wpdb, which is an instantiation of the class already set up to talk to the WordPress database. Always use the global $wpdb variable. (Remember to globalize $wpdb before using it in any custom functions.)


add global $wpdb since you are using it in function, which has local scope .

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.