1

I'm extending the $wpdb object with properties for my custom tables.

function setup_wpdb()
{
    global $wpdb;

    // Create properties for custom tables
    $wpdb->my_plugin_table1 = $wpdb->prefix.'my_plugin_table1';
    $wpdb->my_plugin_table2 = $wpdb->prefix.'my_plugin_table2';
}

Is this a good practice? I guess as long as the properties are prefixed with the plugin name, it should be fine. Defining a constant may work too. What do you prefer and why? Thanks.

1 Answer 1

2

As long as...

  1. You use $wpdb->prefix (or $wpdb->base_prefix) to prefix the table
  2. Your table name is someplace public, and easily available for other plugins, themes and end users to use and extend

I would say either setting the table as a property on $wpdb or using a constant is fine. If you choose to use $wpdb be aware that another plugin (or theme or whatever) can just overwrite your property in the same way you set it. For that reason, it's a bit more "safe" to use something like a constant.

Also, always carefully question whether or not you need to add a table.

I tend to use constants, but if I'm doing something like creating a termmeta table, then I would use a $wpdb property.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.