• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

WP Bitz

A curated collection of code snippets for WordPress

  • Home
  • About
  • Blog
  • Code Snippets
You are here: Home / WordPress Development Tips / Add a Database Connection to use WPDB

Add a Database Connection to use WPDB

WordPress Development Tips · June 3, 2025

This post brought to you by RocketGeek, ButlerBlog, and the following:

 

Suppose you have a secondary database that you need to connect to, but you’d also like to use the methods in the WPDB object to interact with the database in the same way that you work with the primary WP database. Well, here’s a very simple way to do that.

global $odb;
$db_user = "Your DB Username";
$db_pass = "Your DB Password";
$db_name = "Your DB Name";
$db_host = "Your DB Hostname";
$odb = new wpdb( $db_user, $db_pass, $db_name, $db_host );

Now, you can use the global $odb (in this example) the same way you would use $wpdb. You can call this variable anything you want – I just used “odb” for “other database”, but use what makes sense in your situation.

Filed Under: WordPress Development Tips

Chad Butler

This post brought to you by RocketGeek, ButlerBlog, and the following:

 

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

Join for free!

Get free code snippets, WordPress best practices, and practical Content Marketing advice from seasoned WordPress expert Chad Butler (butlerblog):

Recent Posts

  • Add a Database Connection to use WPDB
  • Notice: Function WP_Block_Patterns_Registry::register was called incorrectly
  • Use WP-CLI to back up your site
  • Bitnami WordPress Autoptimize cannot write to the cache directory
  • Create and delete WordPress sites in XAMPP with a batch file

Copyright © 2025 · Maker Pro on Genesis Framework · WordPress · Log in