ajaydsouza
1/8/2014 - 10:31 PM

Add a pseudo static JS file to WordPress

Add a pseudo static JS file to WordPress

<?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' ) );
}