Conditional functions for localhost can be very helpful when developing a WordPress theme. You may be wondering why is this required?
Lets assume, to make the website load faster we load the JavaScript from Google. But while you are working on localhost, it will make the loading slow and use the bandwidth which is not required.
In the example below we will register two jQuery scripts, one to enqueue on localhost and other for the live server.
function custom_conditional_scripts() { wp_register_script('jquery.min',get_template_directory_uri() . '/js/jquery.min.js', '', '1.8.3', false); wp_register_script('google.jquery.min','//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js', '', '1.8.3', false); if (in_array($_SERVER['REMOTE_ADDR'], array('127.0.0.1', '::1'))) { wp_enqueue_script('jquery.min'); } else { wp_enqueue_script('google.jquery.min'); } } add_action('wp_enqueue_scripts', 'custom_conditional_scripts');
In the example above we have used $_SERVER variable to detect the IP address from which the user is viewing the current page and load jquery scripts according to that.
The actual code doing the needful is :
if (in_array($_SERVER['REMOTE_ADDR'], array('127.0.0.1', '::1'))) { //code for localhost }