Should I global $wpdb outside of any of my plugin’s functions scope?

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';.

Read More

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?)

Related posts

Leave a Reply

2 comments

  1. 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" );  
    
  2. 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.