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.

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.

3 Answers
3

$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';
    }
}

Leave a Comment