Enqueue script with url_query variables?

Is there an easy way to enqueue a JavaScript file with url_query values populated?

I have a php file underneath my js directory with JavaScript headers that I want to generate some dynamic JavaScript depending on the url_query values.

Read More

Thanks

Gs

UPDATE:

Yes, in the widget class I added the following (as a test):

(in the constructor, I just wanted to make a completely unique ID so I took the timestamp + a bunch of random #s):

$this->widget_id=time().rand(2,10).rand(2,10).rand(2,10).rand(2,10).rand(2,10).rand(2,10);
add_action('wp_footer', array( &$this, 'footer_js' ));

(then the method):

public function footer_js(){
      wp_register_script( 'mgs-site-script'.$this->widget_id, $this->plugin_location . "js/mgs.js", array('jquery'),'1.2.0');
      wp_enqueue_script( 'mgs-site-script'.$this->widget_id );
      $translation_array = array( 'some_string' => __( 'Some string to translate' ), 'a_value' => '10' );
      wp_localize_script( 'mgs-site-script', 'object_name', $translation_array );
  }

Then in mgs.js I tried to access the variables by calling:

alert(object_name.some_string);

but firebug spits out “object_name is not defined”

Related posts

Leave a Reply

1 comment

  1. 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
    }