0

I'm creating a personal plugin with more files and I need to connect to an external database with WPDB. At the moment I'm repeating "new wpdb(...)" in every function, in every file, of my plugin. Is there any way to put this instruction just ONE time?

0

Use a global.

So, your plugin file would look like this:

$myConn = new wpdb( 'username', 'password', 'database', 'localhost' );

function plugin_step_1( $arg1, $arg2 ) {
    global $myConn;
    //code to do stuff here
}

function plugin_step_2() {
    global $myConn;
    // more code here
}

function plugin_step_3( $arg1 ) {
    //I don't need the wpdb object
}

add_action( 'init', 'plugin_step_1' );
add_action( 'template_redirect', 'plugin_step_2' );
add_action( 'wp_head', 'plugin_step_3' );

Of course, your functions wouldn't necessarily need arguments or whatnot.

Also, note that the way MySQL works, connection persistence may or may not take place, even with a global wpdb object specified in your plugin / functions.php.

Connection persistence (that is, keeping the connection open until all queries are completed for a single page request) generally takes place during an entire page request, but based on when and how your plugin / functions.php goes about calling event handlers for a given request, it may be that WordPress effectively closes the connection before all requests have been made, and thus will open more than one connection, even though you are using a global object to connect.

But, it sounds like your need is mostly about keeping things DRY, rather that persistence or pooling, so this should do the trick.

2
  • I need to Write some data to a database through a form with this plugin. Is this ok with your code? Also, would it be dramatically bad to connect to perform a connection to the database in every single function like I'm doing at the moment? – testermaster Mar 17 '15 at 6:22
  • @testermaster 1. This should work for any DB query, including inserts. 2. Theoretically, your PHP install should persist a single connection, even if you declare it again, so long as the connection is exactly the same (that is, same host / user / pass / db). However, it is far more likely a single, global connection will persist than if you declare it repeatedly; again, this depends on how and when you call the connection(s). – user12479 Mar 17 '15 at 13:40

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.