I have an issue with not being able to call the get_results() function on the $wpdb object inside the WordPress functions.php file.
Exact error: Call to a member function get_results() on a non-object in […]
This is my function;
global $wpdb;
function query_students($year){
$wpdb->get_results(
$wpdb->prepare(
"SELECT * FROM {$wpdb->prefix}usermeta WHERE meta_key ='foobar' AND meta_value = '{$year}'"
)
);
$wpdb->flush();
}
As you can see I’ve globalised the $wpdb variable, and this function works great in the page template file. I would just prefer it if my functions weren’t dotted around the place, and in some kind of centralised file.
Thanks in anticipation! 🙂
“Globalizing” a variable that’s already in global scope does nothing. Case and point:
The global keyword does not permanently make the defined variable global in scope. Think of it as a way to define a variable in a function and set its value to whatever a variable with the same name is outside of the function.
You need to move your global declaration INTO the function to make the $wpdb object in the Global scope available within the function’s scope: