Enqueue script with url_query variables?

I can’t get super specific without a more-detailed example from you, but I think you could combine get_query_var() and wp_enqueue_script() to do what you want like this:

add_action( 'wp_enqueue_scripts', 'sg_scripts' );
function sg_scripts() {

    $current_slug = get_query_var( 'page_name' );
    wp_enqueue_script( 'sg_custom_js', get_template_directory_uri() . '/js/somefile.php?slug=' . $current_slug, $dependencies, $version, $in_footer);

}

(I left the last three arguments as placeholders.)

Admittedly I’ve never tried this. A few things that might give you trouble:

  • I don’t know what happens if wp_enqueue_script() is passed a non-.js file. It might get filtered out.
  • I know that a lot of the caching plugins (and WordPress?) look to the $version arg for caching. If you’re seeing an old version of the js from a recent slug get served, I imagine that’s what’s going on.

Alternately, this is much less dynamic, but you can wrap individual wp_enqueue_script() instances with static .js files in if statements that test the query_var e.g.:

$current_slug = get_query_var( 'page_name' );
if( $current_slug == 'something' ) {
    \\ enqueue a script
} elseif( $current_slug == 'somethingelse' ) {
    \\ enqueue a different script
}
} else {
    \\ enqueue a third script
}

tech