Sending a server-side (WordPress/PHP) development environment variable to your scripts

This is written for PHP and/or WordPress, but the principle applies to any server-side language.

First we’ll we’ll create a php function for determining our environment:

<?php
/**
 * Get development environment key
 */
function get_dev_enviroment() {
    $environment = 1; // production
    if ( false !== stripos( $_SERVER['HTTP_HOST'], 'staging.' ) ) {
        $environment = 2; // dev/staging
    } elseif ( preg_match( '/localhost|127.0.0.1|.dev/', $_SERVER['HTTP_HOST'] ) ) {
        $environment = 3; // local
    } elseif ( isset( $_GET['debug'] ) ) {
        $environment = 4; // manual override (for production, ie. example.com?debug)
    }

    return $environment;
}

This function will return 1 for production, 2 for your staging environment, 3 for your local environment, and 4 if you add a ‘debug’ query variable to your URL (useful if you want to override the production value).

If we’re in WordPress, we would send this variable to our script like so:

$script_source = get_stylesheet_directory_uri() . '/js/my-script.js';
// enqueue
wp_enqueue_script( 'my-script-for-wp', $script_source, array( 'jquery' ) );
// 'localize' our data. Just means add it to the dom as a JS variable
wp_localize_script( 'my-script-for-wp', 'devEnvironment', get_dev_enviroment() );

If we want to include this before a standard script include, add this snippet before your script tag:

<script type="text/javascript">
    window.devEnvironment = <?php echo get_dev_enviroment(); ?>;
</script>
<script type="text/javascript" src="http://example.com/my-script.js"></script>

Then you can use Paul Irish’ handy log snippet (slightly modified) to safely log (won’t break in older browsers) in your development environments:

( function( window, document, $, undefined ) {
    'use strict';

    // http://www.paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
    var log = function() {
        log.history = log.history || []; // store logs to an array for reference
        log.history.push( arguments );
        if ( window.environment && ( [2,3,4].indexOf( window.environment ) > -1 ) && window.console ) {
            window.console.log( Array.prototype.slice.call( arguments ) );
        }
    };

    // log our enviroment variable key
    log( window.enviroment );

    // ... the rest of our script

} ) ( window, document, jQuery );

Comment

Fast, secure WordPress hosting is provided by WP Engine.
%d bloggers like this: