最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Unique ID for WordPress shortcodes when used more than once on a page? - Stack Overflow

programmeradmin6浏览0评论

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 be false for other ID. @diggy – Bir Commented Nov 6, 2014 at 15:30
Add a ment  | 

3 Answers 3

Reset to default 8

You 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>
';
发布评论

评论列表(0)

  1. 暂无评论