Enumerating shortcode attributes in JavaScript

I’m working on a plugin which uses a shortcode to call a JQuery function, and it requires three aspects to work:

  1. The JQuery code + its own code, to be included on the pages it will be used on
  2. The HTML element it will work on requires an “id” attribute, in order to reference it
  3. 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".

Read More

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!

Related posts

Leave a Reply

1 comment

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

    For 1st, add this inside the shortcode function-

    STATIC $flag = false;
    if(!$flag) {
        $flag = true;
    
        // include all your scripts that you want to include in the page only once
        // These statements will be executed once per page load
        // irrespective of how many times shortcode is called.
    }