I’m running a WP site on my laptop using localhost, and I often need my coworkers to see it. If they enter my home’s IP, they were able to access the site, but all the URL’s in WP that used site_url() or similar were echoing out “localhost” which of course didn’t work for outsiders.

So I changed WP to use my IP for the site URL which solved that problem, but created another. If I bring my laptop away from home and try to view my site, now all the links appear as http://home-ip/ which isn’t available. Furthermore, I’m unable to to get into wp-admin to change the site URL back to localhost since I’m being redirected to http://home-ip/site/wp-admin/.

Is there a way to deal with this without having to constantly change the URL every time I want someone else to access it from outside, or every time I leave the house.

3 s
3

You can use wp-config.php to change the site url depending on where the site is accesed from, using $_SERVER['REMOTE_ADDR']. Mine has something like this:

if ($_SERVER['REMOTE_ADDR'] == '127.0.0.1' || $_SERVER['REMOTE_ADDR'] == '::1') { 
    // accesing site from my local server
    define('WP_SITEURL', 'http://localhost/mysite/');
    define('WP_HOME', 'http://localhost/mysite');
} else if (strpos($_SERVER['REMOTE_ADDR'],'192.168.0.') !== false) {
    // accesing site from another machine in my home network, 
    // all their (internal) network addresses begin with this number;
    // the next line provides the server's own internal network address 
    define('WP_SITEURL', 'http://192.168.0.192/mysite/');
    define('WP_HOME', 'http://192.168.0.192/mysite');
} else { //accesing site from outside home
    define('WP_SITEURL', 'http://89.*.*.*/mysite/'); //replace by your external home IP
    define('WP_HOME', 'http://89.*.*.*/mysite');
}
//error_log("Siteurl is ".WP_SITEURL);

This technique also helps a lot to simplify uploading the site to a production server or keeping in sync local and production versions of the site. (Though, obviously, the wp-config.php on the production server should not have this code.)

Note: For some reason, I cannot use my external home IP from other machines in my home network; if that’s not your case, you can remove the else if, leaving only the else part.

Leave a Reply

Your email address will not be published. Required fields are marked *