Skip to content

Instantly share code, notes, and snippets.

@infn8
Last active August 29, 2015 14:13
Show Gist options
  • Save infn8/e4c3f6de8ec7e4a4c919 to your computer and use it in GitHub Desktop.
Save infn8/e4c3f6de8ec7e4a4c919 to your computer and use it in GitHub Desktop.
WP Livereload trigger

Add these files to your theme and ensure that your grunt or gulp or whatever is watching the php files in your theme folder for changes and triggering live reload.

Ensure that yoursite.dev has the live reload script at http://yoursite.dev:35729/livereload.js which it likely will if you're using grunt watch right. If Not edit the livereload-loader.js file to point to the right place where the file is.

<?php
/*
=============================================
Add this stuff to your functions.php
=============================================
*/
function livereload_trigger() {
/*
=============================================
Touch a useless file when triggered
=============================================
*/
$target = get_stylesheet_directory() . '/livereload-trigger.php';
touch($target);
}
function is_dev(){
/*
================================================================
Should return true if you are on a dev site.
I use http://something.dev/ for my local dev so this checks for an occurance
of the string '.dev' in the hostname.
edit this conditional as needed for your own setup
================================================================
*/
return stripos($_SERVER['HTTP_HOST'], '.dev') !== false;
}
/*
================================================================
Add a listener to the save post action if you're on a dev site.
This gets ignored on prod or other testing sites.
================================================================
*/
if(is_dev()){
add_action( 'save_post', 'livereload_trigger' );
}
/*
=============================================
Enqueue Scripts
=============================================
*/
function add_theme_scripts() {
// Get this from http://modernizr.com and be sure to include the websockets test.
wp_register_script( 'modernizr', trailingslashit(get_template_directory_uri()).'js/vendor/modernizr.full.min.js');
/*
===== Dev Only Scripts =====
*/
if(is_dev()){
// wp_register_script( 'livereload-loader', "//".$_SERVER['SERVER_NAME'].":35729/livereload.js" );
wp_register_script( 'livereload-loader', trailingslashit(get_template_directory_uri()).'js/livereload-loader.js', array( 'modernizr' ));
wp_enqueue_script( 'livereload-loader' );
}
}
add_action( 'wp_enqueue_scripts', 'add_theme_scripts' );
?>
// I go in in THEME_DIR/js/
Modernizr.load({
test: Modernizr.websockets,
yep : window.location.protocol + '//' + window.location.host + ':35729/livereload.js'
});
<?php
// I go in THEME_DIR/
/*
Exists only to trigger livereload. Run a touch command on this file to trigger livereload.
*/
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment