Access Another Database in WordPress

When accessing the database in WordPress, you need to use the global variable $wpdb. This will take the constants you set in wp-config.php to connect to your database and retrieve whichever results you specify. But what if you have a second database you wish to connect to for whatever reason? To do that all you need is the following snippet:

$newdb = new wpdb($DB_USER, $DB_PASSWORD, $DB_NAME, $DB_HOST);
$newdb->show_errors();

Add the code snippet to your functions.php file or a specific page template, and then you can use $newdb just like you would $wpdb to access a second database and retrieve some data.

Share this:

Email
Facebook
Twitter
Pinterest
Pocket

Premium Themes for WordPress

Looking for an easy-to-use Premium Theme for WordPress? Check out Themes by bavotasan.com and have your site up and running in no time.

Use this WordPress website builder to build powerful websites in no time for your or your clients.

WordPress Hosting

WP Engine – designed from the ground-up to support and enhance the workflow of web designers.

Bluehost – providing quality web hosting solutions since 1996.

About the author

Picture of Luke Perrie

Luke Perrie