WordPress Connect & Query Blog Posts From A Different WordPress Database
WordPress Connect & Query Blog Posts From A Different WordPress Database
Last week I was building a WooCommerce store for a customer on top of his existing WordPress website. The client already has an existing, high traffic WordPress website so in order to keep the install clean we decided to do a separate install of WordPress on the /shop directory. This would allow us to utilize a different database, have different logins for shop managers, and we thought the overall result would be more organized.
The only catch is we were going to want to share some data (mostly blog posts) between the main site and the online store. This information would primarily be served in the header and footer as the theme was going to stay the same between the two WordPress installs.
In order to achieve this, I wrote a little bit of code to manually extract data from the main WordPress site into this new WordPress/WooCommerce install.
To start, I opened up with the wp-config.php file on this new WordPress install and added the following just below “define(‘DB_COLLATE’, ”);”:
/** Remote Connect DB Name */ define('EXDB_NAME', 'wp_databasename'); /**Remote Connect DB Username */ define('EXDB_USER', 'wp_databaseuser'); /**Remote Connect DB Password */ define('EXDB_PASSWORD', 'thedbpassword123');
The above data should reflect the database name, username, and password from your current WordPress install. This information can basically be copied from the wp-config.php of your current WordPress install, just make sure you add ‘EX’ before each variable so we can leverage that in the actual template file.
I saved my wp-config.php file and moved back to my new WordPress installs footer.php file. I found the location in the footer where I wanted to pull in my most recent posts from the existing blog and I added:
<?php $mydb = new wpdb(EXDB_USER,EXDB_PASSWORD,EXDB_NAME,'localhost'); $rows = $mydb->get_results("select * from wp_posts WHERE post_type = 'post' AND post_status = 'publish' LIMIT 5"); echo "<ul>"; foreach ($rows as $obj) : ?> <li><a href="/<?php echo $obj -> post_name; ?>"><?php echo $obj -> post_title; ?></a></li> <?php endforeach; echo "</ul>"; ?>
What this did is create an unordered list of the five most recent published posts on my existing blog. I can now grab this blog post data from my existing blog even though this WooCommerce shop is running on it’s own version of WordPress in a different sub-directory.
Share Your Thoughts