Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I know that the general advice to global variables is to not use them at all. Still, when doing something with the Wordpress database, it is required to do global $wpdb; to access the methods Wordpress provides for interacting with the database.

Now I've written a small plugin that introduces several functions that need to interact with the Wordpress database. That means, in every function I have written global $wpdb;. After that, I build the table names needed dynamically: $wpdb->prefix . 'my_table_name';.

This is a lot of redundant code in my opinion that even can produce a lot more work. For example, I changed the table names a few times during development and had to change it in every function of my plugin where I do $wpdb->prefix . 'my_table_name';.

Now my question is: Is it a good idea to just global $wpdb outside of any function scope and then assign the tables names to global variables?
That way, everything would be a lot more flexible regarding table names (and maybe even performance?)

share|improve this question

2 Answers 2

up vote 4 down vote accepted

A convenient way to use $wpdb in plugins, with custom tables and custom functions is write a class or a couple of functions that get the wp object, and configure it.

An example:

/* Return global wpdb aready setup with custom tables */
my_plugin_get_db( wpdb $wpdb = NULL ) {
  static $db;
  if ( is_null($db) || ! is_null( $wpdb ) ) {
    $db = is_null($wpdb) ? $GLOBALS['wpdb'] : $wpdb;
  }
  return $db;
}

/* Setup database saving $wpdb custom table names insie wpdb object */
my_plugin_set_db() {
  global $wpdb;
  /* define here your custom table names */
  $my_tables = array(
    'my_table_1', 'my_table_1', 'my_table_1'
  );
  foreach ( $my_tables as $table ) {
     $wpdb->$table = $wpdb->prefix . $table;
  }
  my_plugin_get_db( $wpdb );
}

add_action( 'plugins_loaded', 'my_plugin_set_db' );

/* Multisite compatibility? */
if ( is_multisite() ) {
    add_action( 'switch_blog', 'my_plugin_set_db' );
}

After that wherever in your plugin you can use

$db = my_plugin_get_db();
$query = $db->query( "SELECT * FROM $db->my_table_1" );  
share|improve this answer
    
Thats a cool piece of code, thank you! –  Sven Apr 13 at 18:16

Globalizing WordPress-defined vars is not the same as creating your own global variables. In the former, you have no choice, it's the latter which you can choose to avoid. Wrap your functions in a class and define your table name as a member var. This lets you define it in one place and keeps it out of the global scope.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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