admin管理员组文章数量:1134248
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?
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?
Share Improve this question asked Mar 16, 2015 at 12:07 testermastertestermaster 2134 silver badges16 bronze badges1 Answer
Reset to default 0Use 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.
本文标签: wpdbPlugin with connection to databaseSingle function
版权声明:本文标题:wpdb - Plugin with connection to database - Single function 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736825412a1954468.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论