Serving CSS/JS Depending On ENV Variable In Staging & Production WordPress Deployment

WordPress Tutorials by Allure Web Solutions

In this post, I show how to setup a simple environment based configuration for your WordPress site. It’s useful in situations where you’re using minification/concatenation in your build depending on your development versus production environments.

How To Set Environment

Place the below code in your wp-config.php file. Or, if you have a .env file you use, you can define this variable there.

define('ENV', 'development');

Check For Environment And Setting Correct Path For CSS/JS

The below code assumes your dev environment assets are located in the build folder and production/staging assets are located in the dist folder. If in your case they are located in the same folder, you can just remove that piece of code. Basically, adjust the paths as needed.

// Check Environment
if (WP_ENV === 'development') {
    $GLOBALS['$asset_root'] = 'build';
    $GLOBALS['$styles']     = "style.css";
    $GLOBALS['$js']         = "main.js";
} else {
    $GLOBALS['$asset_root'] = "dist";
    $GLOBALS['$styles']    = "style.min.css";
    $GLOBALS['$js']         = "main.min.js";
}

/**
 * Theme assets
 */
add_action('wp_enqueue_scripts', 'theme_assets');
function theme_assets()
{
    // CSS
    wp_enqueue_style('css', get_stylesheet_directory_uri() . '/' . $GLOBALS['$asset_root'] . '/css/' . $GLOBALS['$styles']);

    // JS
    wp_enqueue_script('js', get_stylesheet_directory_uri() . '/' . $GLOBALS['$asset_root'] . '/js/' . $GLOBALS['$js'], array('jquery'), '1.0', true);
}


Mike Doubintchik

Author Mike Doubintchik

More posts by Mike Doubintchik

Leave a Reply