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?
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,
});
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?
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,
});
Share
Improve this question
edited Nov 6, 2014 at 15:18
Bir
asked Nov 6, 2014 at 15:05
BirBir
8121 gold badge17 silver badges31 bronze badges
2
-
1
Is an ID necessary? You could use a class
.demo
instead – diggy Commented Nov 6, 2014 at 15:23 -
Yes you solution will work. But
autoplay
can befalse
for other ID. @diggy – Bir Commented Nov 6, 2014 at 15:30
3 Answers
Reset to default 8You can use a static variable
static $i = 1;
$i++;
and use it as part of the ID
return "<div id='shortcode-div-{$i}'></div>";
You are free to set the shortcode’s id among with other parameters:
[gallery id="123" size="medium"]
I would remend 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>
';