Localhost / Web switch function

Published: On Tuesday, January 13, 2009

Sometimes happens to me, that the (db) content of WP site is simply out-of-sync with the copy running on localhost. I'd like to do some changes, let's say add Pages and since I want to do it fast, I don't care about synchronisation (which means 1. sql dump download 2. sql import 3. modifications in wp_options).

In these cases of unsynchronized databases, I often encounter the fact of different IDs: a new page created on localhost first won't finally have the same post-ID online. Now, I need to use in template a condition like is_page(...) — but I know, it will work either on localhost or on the web. Following simple switch-like-working function can be the solution.

Usage

if (is_page(webOrNot(457, 422))) {
        // do something
}

Function

function webOrNot ($web, $lh) {

        if (false === strpos($_SERVER['HTTP_HOST'], 'localhost'))
                return $web;
        else
                return $lh;

}

Sure, this can't be called best practice, but you may meet other situations, when the db sync doesn't matter. Let's say – thanks to this function (might be better to say – condition :)) you can use same wp-config.php for web and localhost too.

...
define('DB_PASSWORD', (false === strpos($_SERVER['HTTP_HOST'], 'localhost')) ? 'onlinePassword' : 'localPassword');
...

Comments

  1. 1.  OndroNR wrote: On January 14., 2009 comment number 1

    can I add something to ENV vars on dev server and a identify it by that var?

  2. 2.  Kahi [author] wrote: On January 14., 2009 comment number 2

    ↪ OndroNR I'm not sure what do you mean by „ENV vars“…

  3. 3.  OndroNR wrote: On January 15., 2009 comment number 3

    I mean $_ENV.. can I add new item to it using apache or lighthttpd?

  4. 4.  OndroNR wrote: On January 15., 2009 comment number 4

    little testing and it works :) I just added new environmental variable through Windows interface, restarted apache (config reload; php as module) and this works now
    echo (getenv('phptest') == 'devmachine') ? 'devmachine' : 'productionmachine';

  5. 5.  Kahi [author] wrote: On January 15., 2009 comment number 5

    ↪ OndroNR I see, never heard of $_ENV before :-).

  6. 6.  Anonymous wrote: On August 15., 2009 comment number 6

    or try this.. COMPUTERNAME ENV var is present on my Vista SP2 machine.. echo (getenv('COMPUTERNAME') == 'TRON') ? 'devmachine' : 'productionmachine'; you just don't have to add any ENV var.. just viewed linux phpinfo.. there is no COMPUTERNAME :( so if you are working on Windows, this is an option

I quit working with WordPress, comments are closed. My plugins will not be updated any more – at least not by me. Feel free to modify my source codes though… Also I am not able to provide support, sorry. –Kahi