Functions.php code that only runs on localhost?

I would like to run an add_action in functions.php only if the theme is being loaded from my localhost development site. How would I get this to run only on localhost?

function livereload(){
?>
    // mycode
 <?php
}
add_action('headway_body_close', 'livereload');

Related posts

Leave a Reply

3 comments

  1. This is the corect answer

    if ( $_SERVER["SERVER_ADDR"] == '127.0.0.1' ) {
        function livereload(){
        ?>
            // mycode
         <?php
        }
        add_action('headway_body_close', 'livereload');
    }
    
  2. A rather safe way is marking your local environment as such in your local wp-config.php.

    Example:

    // wp-config.php
    define( 'WPSE54453_IS_LOCAL_SERVER', TRUE );
    
    // functions.php
    defined( 'WPSE54453_IS_LOCAL_SERVER' ) 
        && WPSE54453_IS_LOCAL_SERVER 
        && add_action( 'headway_body_close', 'livereload' );
    

    This is also a question of readability. You can see immediately what the code does.

  3. The easiest way to do it to check IP address of an user. If it equals to 127.0.0.1, then this user running the site on localhost.

    if ( $_SERVER['REMOTE_ADDR'] == '127.0.0.1' ) {
        function livereload(){
        ?>
            // mycode
         <?php
        }
        add_action('headway_body_close', 'livereload');
    }
    

    UPDATE: or as mentioned @Tommixoft you can check server IP address.

    if ( $_SERVER['SERVER_ADDR'] == '127.0.0.1' ) {
        function livereload(){
        ?>
            // mycode
         <?php
        }
        add_action('headway_body_close', 'livereload');
    }