How can I connect to another WP database and use WP_Query?

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

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;

Leave a Comment