[wp-hackers] Using wp_localize_script() more than once for same script

Ade Walker photofantaisie at gmail.com
Tue Jan 31 13:18:52 UTC 2012


The title of this post may be a little misleading, so I'll explain what I'm
trying to do and hopefully the question I'm trying to ask will be clearer...

I've created a widget that displays a jquery carousel. The carousel's
scripts are being enqueued mid-page via add_action('wp_footer', array(
$this, 'enqueue_scripts') ) within the widget's widget() method. The
enqueue_scripts() method does the actual enqueueing using
wp_enqueue_script() with $footer arg set to true. Additionally, since there
are various parameters for the script managed via the widget's control
panel, I also use wp_localize_script() to send these PHP parameters to
javascript [see note 1 below]. All of this works perfectly.

However, I want to allow the widget to be used more than once on the same
page. The jQuery script itself can handle this OK, but I cannot assume that
the parameters used by the js will be identical for all instances of the
widget.Therefore, I need a way of using wp_localize_script() more than once
for the same script $handle, so that each widget instance can use
wp_localize_script() with its own set of parameters. From what I can see,
this isn't possible because wp_localize_script will only output one set of
parameters per file $handle.

What I'd like to have is this (or variation thereof) if two widget
instances are present on the same page:
https://gist.github.com/1710421whereas what is actually output is only
the parameters for the last
instance of the widget, not both instances.

Do I have an alternative other than to go back to the "bad old days" of
echoing out script tags via the wp_footer hook?

Hope my question makes sense. Thanks in advance for any insight!


More information about the wp-hackers mailing list