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.
$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:
Eugene Manuilov answer is a good solution. However if you want use the
$wpdb->table_name
syntax you canDo 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:And then in your queries use it like this:
UPDATED:
Those tables are set when
$wpdb->set_prefix()
method is called. Take a look at this method and you focus on 673-685 lines.