2

I can connect to the other database with $db2 = new wpdb( $user, $pass, $db, $host );, but how to I get WP_Query() to use $db2?

I want to be able to use the loop just the same with $db2 as I can with the original connection.

1 Answer 1

8

WP_Query uses the global $wpdb. What you'll have to do is replace $wpdb, use WP_Query, then set it back when you're done.

global $wpdb; $wpdb_backup = $wpdb; $wpdb = new wpdb( $user, $pass, $db, $host ); # Do your stuff here... # then when done... $wpdb = $wpdb_backup; 
6
  • @s_ha_dum Hah, it's gone the other way a few times lately! I think your fingers are usually a little quicker than mine. Commented May 24, 2013 at 20:13
  • and how could we close that new connection ..? Commented Jun 20, 2013 at 10:15
  • This didn't work for me out of the box. Had to set the prefix as well $wpdb->prefix('wp_');. Commented Mar 27, 2017 at 7:08
  • A late but valid comment... it is important to call wp_flush_cache() after setting $wpdb to the new connection and again when assigning it back to $wpdb_backup. Sometimes you are still connected to the previous database and calling wp_flush_cache() ensures that you are not. Commented Aug 5, 2018 at 9:53
  • @joehanna wp_cache_flush() not wp_flush_cache() Commented Oct 23, 2020 at 19:53

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.