Skip to content

Instantly share code, notes, and snippets.

@pingram3541
Last active July 29, 2019 16:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pingram3541/53c91ea7076d911c01b33a44e8fb4da7 to your computer and use it in GitHub Desktop.
Save pingram3541/53c91ea7076d911c01b33a44e8fb4da7 to your computer and use it in GitHub Desktop.
Wordpress Inline Script with Fallback
<?php
/**
* see - https://digwp.com/2019/07/better-inline-script/
* by - Jeff Starr
*/
// enqueue scripts
function shapeSpace_enqueue_scripts() {
wp_enqueue_script('shapeSpace_script', get_template_directory_uri() .'/js/script.js', array(), '1.0', true);
shapeSpace_inline_script();
}
add_action('wp_enqueue_scripts', 'shapeSpace_enqueue_scripts');
// inline scripts WP >= 4.5
function shapeSpace_inline_script() {
$wp_version = get_bloginfo('version');
if (version_compare($wp_version, '4.5', '>=')) {
$script = 'var1 = '. json_encode('var1') .'; ';
$script .= 'var2 = '. json_encode('var2') .'; ';
$script .= 'var3 = '. json_encode('var3') .'; ';
wp_add_inline_script('shapeSpace_script', $script, 'before');
}
}
// inline scripts WP < 4.5
function shapeSpace_print_scripts() {
$wp_version = get_bloginfo('version');
if (version_compare($wp_version, '4.5', '<')) {
?>
<script>
var var1 = <?php echo json_encode('var1'); ?>;
var var2 = <?php echo json_encode('var2'); ?>;
var var3 = <?php echo json_encode('var3'); ?>;
</script>
<?php
}
}
add_action('wp_print_scripts', 'shapeSpace_print_scripts');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment