Where do I add a new table’s name in wpdb?

I’ve manually setup a new table in the wp-db database. Where do I add the name of this table in the wpdb class or anywhere else?

I’ve noticed that WordPress uses queries like:
$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->users" ); where the actual table name isn’t used.

Read More

If I were to do:
$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->friends" ); it will not work.

I also tried adding the name like var $friends; inside the wpdb class, but that would not work.

Related posts

3 comments

  1. $wpdb->tables[] = 'friends'; is the basic code you’re looking for.

    Please note that you’ll want to test for the existence of the table in the list so you don’t wind up with 100 copies of the table in the tables array, especially if there’s a chance your code could be repeated within a page load.

    UPDATED with example:

    add_action( 'wp_loaded', 'add_table' );
    
    function add_table() {
        global $wpdb;
        if ( ! in_array( 'friends', $wpdb->tables ) ) {
             $wpdb->tables[] = 'friends';
        }
    }
    
  2. Eugene Manuilov answer is a good solution. However if you want use the $wpdb->table_name syntax you can

    add_action('after_setup_theme', 'add_table_name');
    
    function add_table_name() {
      global $wpdb;
      $wpdb->friends = $wpdb->prefix . 'friends';
    }
    
  3. Do not modify your wpdb class at all! It’s a bad habit. Next time when WordPress update it’s version you will loose all your changes.

    Instead of modifying wpdb class, create a table name variable (or constant) withing your plugin and use it when you need it.

    For instance, in your myplugin.php file add following:

    global $wpdb;
    define( 'MYPLUGIN_TABLE_FRIENDS', $wpdb->prefix . 'friends' );
    

    And then in your queries use it like this:

    $user_count = $wpdb->get_var( "SELECT COUNT(*) FROM " . MYPLUGIN_TABLE_FRIENDS );
    

    UPDATED:

    Ok. Fine. But just for my knowledge, since I’m new to all this, how
    does WordPress do it, and where are they stored?

    Those tables are set when $wpdb->set_prefix() method is called. Take a look at this method and you focus on 673-685 lines.

Comments are closed.