jcadima
4/28/2016 - 12:47 AM

Fetch data from more than one Wordpress database

Fetch data from more than one Wordpress database


https://wordpress.org/support/topic/can-i-reassign-global-wpdb-object-in-a-theme?replies=4#post-1481489

https://wordpress.org/plugins/hyperdb/


1. call first db db1
2. call second db db2
3. have table prefix on first db set to prefix1_
4. have table prefix on second db set to prefix2_
5. installed hyperdb plugin from:
http://wordpress.org/extend/plugins/hyperdb/
(followed instructions in readme file).

6. configured hyperdb db-settings.php file to read from the 2 dbs by adding the two databases via add_db_server();
add_db_server('global', 0, '', 1, 1, DB_HOST, DB_HOST, DB_NAME, DB_USER, DB_PASSWORD);
add_db_server('db2', 0, '', 1, 1, DB_HOST, DB_HOST, 'db2', DB_USER, DB_PASSWORD);

7. Also inside db-settings.php of hyperdb I told hyperdb to query the second database for all tables belong to that database using a call to add_db_table (i added all tables via the method call like so):
add_db_table('db2', 'prefix2_commentmeta');
add_db_table('db2', 'prefix2_comments');
add_db_table('db2', 'prefix2_links');
add_db_table('db2', 'prefix2_options');
add_db_table('db2', 'prefix2_postmeta');
add_db_table('db2', 'prefix2_posts');
add_db_table('db2', 'prefix2_terms');
add_db_table('db2', 'prefix2_term_relationships');
add_db_table('db2', 'prefix2_term_taxonomy');
add_db_table('db2', 'prefix2_usermeta');
add_db_table('db2', 'prefix2_users');

6. finally, inside the code where I wanted to read second db posts on first site, I did the following:

global $wpdb;
$wpdb->set_prefix('prefix2_');

do all my processing...
then change prefix back to original inside wpdb object

$wpdb->set_prefix('prefix1_');