In main.js, I have a script, which is sending an ajax request to script.php.

    type: "POST",
    url:  "wp-content/themes/roots/script.php",
    data: registerdata,
    success: function(result)
return false;

script.php validate some data and write the data into the database. For this, I use the $wpdb object by WordPress ($wpdb->insert()). Normally, WordPress provides a global variable, $wpdb, which is an instantiation of the class already set up to talk to the WordPress database. But not in my case. I get the following error

Fatal error: Call to a member function insert() on a non-object

If I do

if(class_exists('wpdb') == false){
    echo 'class wpdb doesnt exist';
    echo 'class wpdb exists';

in script.php, it told me all the time 'class wpdb doesnt exist'. If I do the same in function.php, class wpdb exists. But why? Script.php and function.php are in the same directory. And $wpdb is auto loaded and set up to global by WordPress. So I have access all the time, doesn't matter in which directory I am, right?!

realpath(ABSPATH . WPINC . '/wp-db.php')

.... also doesnt work. Constants are undefined in script.php, too. Where is my fault? register_globals = on in php.ini. changed nothing. :/

  • 4
    Read wordpress.stackexchange.com/questions/9231/… – you have to use the AJAX API.
    – fuxia
    Apr 9, 2013 at 8:22
  • 2
    Also I'd recommend against doing raw SQL when a custom post type would suffice, AND avoid the roots theme, it's poorly built and introduces more problems than it solves
    – Tom J Nowell
    Apr 9, 2013 at 8:40

1 Answer 1


To answer your question directly, yes, $wpdb is "auto loaded and set up to global by WordPress" but by loading wp-content/themes/roots/script.php directly you are skipping over the WordPress boot process and loading the file exactly as if WordPress did not exist. That is why the normal WordPress objects and constants aren't available. They haven't been loaded, because WordPress hasn't been loaded. You get the same problem, or similar, trying to load any other template or plugin file out of sequence.

The directory the file(s) are in is irrelevant. Files are not "autoloaded" just because they are in a particular directory, with a couple of specific exceptions-- with template hierarchy files for example-- and that only works because WordPress was written to look for and load particular files from particular places.

As stated in a comment to the question, you need to be using the AJAX API. There are plenty of questions here to help with that not to mention tutorials in other places and the Codex itself.

  • thanks to all of you! everything works great now with the AJAX API! :) Apr 10, 2013 at 6:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.