Unique ID for WordPress shortcodes when used more than once on a page?

I’m currently coding a WordPress shortcode and it has some jquery involved. For jquery to work properly I need to use a div with a unique #ID. If the shortcode is used once, it works fine, but if they were to use the shortcode more than once on a page, it would break the javascript.

So, I’m wondering if there is some way to use a unique ID every time the shortcode is called? Or some way to have a different ID if the shortcode is used more than once on a page?

Read More

Suppose i have the shortcode function

function my_shortcode() { 
 $my_shortcode='<div id="demo">My content</div>'; 
 return $my_shortcode;
} //end function 

and jquery

 $("#demo").click(function{

    autoplay: true,
});

Related posts

Leave a Reply

3 comments

  1. I would recommend using an UUID.

    In my projects I generate it and attach it the the $atts element.

    add_shortcode('some_shortcode', function ($atts, $content = null) {
      ...
    
      $atts['uuid'] = uniqid();
      ...
    
      return 'I have a unique ID: ' . $atts['uuid'];
    }
    

    This can be easily attached to a data attribute, e.g.

    return echo '
      <div data-group-uuid="' . $atts['uuid'] . '">
        I'm a container with a unique ID
      </div>
    ';