0

How can I call the wpdb inside a plugin function defined in a class like this,

<?php

/*
*   Plugin Name: Test
*   Plugin URI: http://www.test.com/
*   Description: Test plugin for wordpress.
*   Version: 1.0.0
*   Author: Test
*   Author URI: http://test.me/
*/      

class Test {

    /*
    |------------------------------------
    | Constructor
    |------------------------------------
    */

    public function __construct() {

    }

    public function abc() {
        var_dump($wpdb);
    }
}

1 Answer 1

3

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

You need to use it like this.

global $wpdb;
//do something with it.
Sign up to request clarification or add additional context in comments.

4 Comments

Where to put this in my class?
at every places where you want to use if you using in any function than put it in function or else in class.
Given the code example above please indicate how to access that global variable from within the plugin class. Please show code.
You can pass the $wpdb global to your class when you instantiate the class ` $example = new exampleClass($wpdb);` Then in the constructor you can attach the $wpdb object to the class with $this->wpdb = $wpdb ` public function __construct($wpdb){ $this->wpdb = $wpdb; }`

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.