Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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');
share|improve this question
add comment

3 Answers

up vote 2 down vote accepted

This is the corect answer

if ( $_SERVER["SERVER_ADDR"] == '127.0.0.1' ) {
    function livereload(){
    ?>
        // mycode
     <?php
    }
    add_action('headway_body_close', 'livereload');
}
share|improve this answer
    
it doesn't mean that my answer is wrong. your answer is almost identical to my. –  Eugene Manuilov Jun 7 '12 at 9:27
add comment

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');
}
share|improve this answer
    
$_SERVER['REMOTE_ADDR'] shows client IP not server ip. –  Tommixoft Jun 7 '12 at 9:23
    
@Tommixoft thanks for mention –  Eugene Manuilov Jun 7 '12 at 9:27
    
127.0.0.2 is local too. And many other IP addresses. Oh, and don’t forget IPv6. –  toscho 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). –  toscho Jun 7 '12 at 9:50
show 5 more comments

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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