4

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');
5

This is the corect answer

if ( $_SERVER["SERVER_ADDR"] == '127.0.0.1' ) {
    function livereload(){
    ?>
        // mycode
     <?php
    }
    add_action('headway_body_close', 'livereload');
}
  • it doesn't mean that my answer is wrong. your answer is almost identical to my. – Eugene Manuilov Jun 7 '12 at 9:27
  • With Xampp SERVER_ADDR or REMOTE_ADDR returns '::1', so I check if SERVER_NAME is 'localhost' instead. (Since this is the accepted answer, I copy my comment here as well.) – Guney Ozsan Oct 19 '18 at 18:38
5

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.

1

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');
}
  • $_SERVER['REMOTE_ADDR'] shows client IP not server ip. – Tommixoft Jun 7 '12 at 9:23
  • 127.0.0.2 is local too. And many other IP addresses. Oh, and don’t forget IPv6. – fuxia Jun 7 '12 at 9:42
  • @toscho we are talking about development pc. have you setup ipv6 on your localhost? Or maybe you use 127.0.0.2 instead? ;) – Eugene Manuilov Jun 7 '12 at 9:46
  • @EugeneManuilov In fact, I use not just 127.0.0.2 but many more addresses. Not IPv6 … yet. There are also local networks (here: 192.168.56.1 and more). – fuxia Jun 7 '12 at 9:50
  • @toscho what for do you use 127.0.0.2? – Eugene Manuilov Jun 7 '12 at 9:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.