Registering custom tables in WordPress is very easy and it is something I do all the time because it saves me a lot of typing and more importantly because 90% of the work I do involves doing CRUD on custom tables.
Things To Consider
The most important thing to consider is that you don’t override WordPress tables and that you communicate with the rest of your team how to access these tables via the $wpdb
global variable.
Come up with a naming convention and stick to it. I like the accessor property to match the table’s name without the prefix so if my table’s name is wp_galleries
then I register the table as galleries
so I can access it like this $wpdb->galleries
.
Registering Custom Tables
In our example, we are going to register a couple of tables for a Galleries plugin. These are the actual tables that would be in our database.
- wp_galleries
- wp_gal_images
- wp_gal_likes
- wp_gal_comments
With this in mind, let’s look at how I would handle this table and register them under $wpdb
so I can use them later.
add_action( 'init', 'register_tables', 1 );
/**
* Register tables.
*/
function register_tables() {
$tables = [
'galleries',
'gal_images',
'gal_comments',
'gal_likes',
];
global $wpdb;
foreach ( $tables as $table ) {
$wpdb->$table = $wpdb->prefix . $table;
$wpdb->tables[] = $table;
}
}
How To User These Custom Tables
Using these tables is very easy, you can now refer to any of these via the global $wpdb
variable.
global $wpdb;
// Now you can access these tables via these
$wpdb->galleries;
$wpdb->gal_images;
$wpdb->gal_comments;
$wpdb->gal_likes;
SQL Statement
global $wpdb;
$limit = 3;
$sql = "SELECT * FROM $wpdb->galleries LIMIT %d;";
$stmt = $wpdb->prepare( $sql, $limit );
$galleries = $wpdb->get_results( $stmt );
That’s it.