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

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