Paulund
2013-09-21 #wordpress

Get Database Table Prefix In WordPress

If you are using WordPress multisite then depending on what blog you are using the database table prefix will be different. By default the WordPress database table prefix is wp_, you can change this prefix in the wp-config.php. To change the database table prefix add a variable of $table_prefix to the wp-config.php file.


/**
 * WordPress Database Table prefix.
 *
 * You can have multiple installations in one database if you give each a unique
 * prefix. Only numbers, letters, and underscores please!
 */
$table_prefix  = 'newprefix_';

When you are using WordPress multisite the blog ID will be added to the end of the database table prefix.


// Site 2 prefix
newprefix_2_

// Site 3 prefix
newprefix_3_

To get data from your database WordPress uses a database class defined as $wpdb, you can get access to this object in any of your functions simply by using the global keyword.


function code_function()
{
    global $wpdb;
}

The information you can get from this class is very useful when interacting with the database, this will store the last query, the last result and current site it needs to query. If you are making custom queries to the WordPress database you should use this object to get the information for the current site. There is a property which is defined as prefix to get the current site database prefix.


global $wpdb;

// Current site prefix
echo $wpdb->prefix;

If you are on the main site or have a single site install this value will stay the same, but on mutlisite installs of WordPress this property will change to whatever site you are on. If I were to switch to site ID 2 then $wpdb->prefix will be newprefix_2_.


global $wpdb;

// Output newprefix_2_
echo $wpdb->prefix;

But there may be a time where you want to get the value of the prefix that was defined in the wp-config.php, even on a multisite blog. To get this value you need to use another property available in the $wpdb class defined as $wpdb->base_prefix.


global $wpdb;

// current site prefix
echo $wpdb->prefix;

// wp-config.php defined prefix
echo $wpdb->base_prefix;

UpChecker

Reliable uptime monitoring and instant alerts for any website downtime.

  • Uptime Monitoring
  • Performance Monitoring
  • SSL Certificate Alerts
  • Domain Monitoring
  • DNS Checker
  • XML Sitemap Monitoring