I’m working on a plugin which uses a shortcode to call a JQuery function, and it requires three aspects to work:
- The JQuery code + its own code, to be included on the pages it will be used on
- The HTML element it will work on requires an “id” attribute, in order to reference it
- A reference/initialization in a
$(document).ready(function())
block
I’ve already implemented 1 and 2; 1 by using wp_register_script
and, if the shortcode appears, wp_print_scripts
to print it; and 2 by making “id” an attribute of my shortcode, which also gets returned, e.g. [myshortcode id="foo"]
returns id="foo"
.
The problem is 3. The initialization is of the form:
$(document).ready(function()
{
$("#id").func( {attributes} );
}
);
I’ve considered using wp_localize_script
over a variable for the ID; however, I do not know how many times the shortcode will appear on a given page, and it seems sloppy to register an arbitrary number of otherwise-identical scripts and just hope that the number won’t be surpassed.
This seems like it’s probably pretty common, but I haven’t been able to find anything related by searching. Any ideas? Thanks!
For 2nd, i recommend using the php function
uniqid()
, takes some of the work of user.For 3rd i think the best way to implement is to keep adding the id’s after each shortcode call to a global/static variable in an array & then hook a function to
wp_footer
that reads from this variable to get all the id’s & generate the neccessary javascriptFor 1st, add this inside the shortcode function-