WordPress Database From Multiple Hosts

As I discussed in a previous post, I like to develop locally using MAMP. This means I keep two separate copies, a development version locally, and a release version on the server. See my previous post for info on how to set up WordPress using MAMP.

When you're running your development copy, you'll often want it to use the content from your live site. That's fine, we can connect to our live database from our local version no problem (providing your MySQL server allows remote access), the problems lies within the WordPress configuration. Within the WordPress configuration you are given two options relating to the URL of your site:

WordPress Address - the location of the WordPress core files. Example: https://example.com/wordpress/
Site Address - your site's root URL. Example: https://example.com

These values are stored in the database, meaning if your database is set up for your live site but you're trying to run it from your local site, you'll get all sorts of problems occurring.

We can get around that by doing the following:

  1. Go into /wp-includes/ and open up option.php.
  2. Find get_option() (should be near the top of the file).
  3. Insert the following at the very top of the function, just after any variable definitions. It should look like this:
    function get_option( $option, $default = false ) {
    	global $wpdb;
    
    if ($option == "siteurl" || $option == "home") {
        /* Are we looking at dev site? */
        if (strpos($_SERVER["SERVER_NAME"], "example.dev") !== false)
           return "https://example.dev";
    }
    /* Continue as normal if we aren't looking at the dev site */
    

This allows us to keep an exact duplicate of the code both locally and on the server.

© 2020 Dec Norton