Last active
April 7, 2017 22:00
-
-
Save retgef/8325711 to your computer and use it in GitHub Desktop.
Add a pseudo static JS file to WordPress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
#Add a query var to sniff requests | |
add_filter( 'query_vars', 'my_query_var_callback', 10, 1 ); | |
function my_query_var_callback( $vars ){ | |
$vars[] = 'dynamic_js'; | |
return $vars; | |
} | |
#Dynamic JavaScript | |
add_rewrite_rule( '^assets/js/dynamic\.js$', 'index.php?dynamic_js=1', 'top' ); //Note the hidden query variable | |
#Sniff Requests | |
add_action( 'template_redirect', 'sniff_dynamic_js', 1 ); | |
function sniff_dynamic_js(){ | |
$js = get_query_var( 'dynamic_js' ); | |
if( $js ){ | |
header('Content-Type: application/javascript'); | |
#Add caching headers | |
#Output your content here | |
exit; | |
} | |
} | |
#Queue it up | |
add_action( 'wp_enqueue_scripts', 'my_enqueue_callback', 10 ); | |
function my_enqueue_callback(){ | |
wp_enqueue_script( 'dynamic-js', '/assets/js/dynamic.js' ) ); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment