Support » Plugins » Hacks » $wpdb not being defined in function

  • For some reason the $wpdb object is not being defined in one particular function. I’m working locally here and I have four other functions in the file that are using $wpdb and all are working fine except this one simple delete function where I get the error: Call to a member function query() on a non-object… The following is the function in question:

    function delete_gallery( $gallery_id ) {
        global $wpdb;
        $sql = "DELETE from galleries WHERE gallery_id = $gallery_id";
        $deleted = $wpdb->query( $sql );

    I have a link (delete gallery) on the plugin admin settings page that links to delete-gallery.php that calls the delete function and returns back to the admin page. The contents of that file are:

    include 'ga-functions.php';
    if (isset($_GET['gallery_id'])) {
    	$gallery_id = $_GET['gallery_id'];
    	wp_redirect( $_SERVER['HTTP_REFERER'] );

    If I var_dump on the $wpdb after initializing I get the result of NULL. Anyone have any suggestions on what could be causing this in only one particular function like this.

Viewing 2 replies - 1 through 2 (of 2 total)
  • If that’s all the code that you have for that, then it means that your delete function is being run before anything is set up, so the $wpdb variable hasn’t been initialised by the WP core yet. Are you calling that finction directly from the plugin file, or is the function registered suing add_action()?

    The function was being registered with the ‘init’ action hook but I could never get it to work. The anchor link that is clicked is on the plugin settings page which links to the delete-gallery.php file. This file is where the action hook is registered and the function is called.

    I’ve since replaced the anchor link with a submit button on the settings page and have it working by just calling the function from the plugin file. Not sure if this is the best way to remedy the problem, but nonetheless, it solved it and it’s updating the db as expected.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘$wpdb not being defined in function’ is closed to new replies.