Local environment widget

tdrayson

A snippetclub.com member was running into issues where they had both a local version and online version of the same site and wondering why changes weren’t reflecting on the frontend.

I wrote a quick snippet that checks if the environment is local and adds a widget in the top right corner. This works with LocalWP as they set the constant WP_ENVIRONMENT_TYPE to LOCAL. This makes our life easy for checking in the code.

screenshot 2023 08 30 at 14.43.38

Snippet

Add the code below to functions.php or code snippet plugin.

PHP

        add_action("wp_head", "local_checker");
function local_checker(){
    if(!defined( 'WP_ENVIRONMENT_TYPE' )) return;
    if (WP_ENVIRONMENT_TYPE == "local") {
        echo '<style>
            body::before{
                content:"Local environment"; 
                position: fixed;
                top: 40px;
                right: 10px;
                z-index: 9999999;
                background: lightcoral;
                border: 1px solid lightgray;
                padding: .5rem 1rem;
                border-radius: 4px;
                box-shadow: rgba(149, 157, 165, 0.2) 0px 8px 24px;
            }</style>';
    }
}

      
Copy

👋🏻 Weekly Tutorial Digest

I send out a weekly newsletter with links to new tutorials written in the last week, you can subscribe below.

Newsletter

🔒I won't send you spam, I promise