WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Suppose I have a shortcode called [item], which I have used 20 times in a particular post.

Is it possible, from within the shortcode handler function, to know what the numerical index of the given [item] is? Like, whether this is the 1st [item] in the post, or the 16th?

I know that I would be able to achieve the same result by manually adding an attribute, such as [item order="1"] and [item order="16"], but I want to make things as easy as possible when adding and rearranging content. Items are often added, deleted and rearranged in the editing process, and it would be tedious and prone to error for the author and editor to re-number them with every change.

Is there a good way to do this?

Would it require global variables? Is that bad?

share|improve this question
up vote 2 down vote accepted

If you're using a class, it would be

class MyShortcode {

static $instance = 0;

    function __construct($args = array()) {
      add_action( 'init', array(&$this, 'init') );

    function init() {
      add_shortcode('myshortcode', array(&$this, 'shortcode'));

    static function shortcode($atts) {
      //this is the code of your shortcode

      // you can increment your counter


share|improve this answer
Remember to reset $instance after each post, otherwise the counts are messed up when you view a list of posts. – Raphael Jul 28 '12 at 14:47
I'm new to OOP; how would I initialize this to get the shortcode registered? – supertrue Aug 1 '12 at 18:10
How do I reset the $instance after each post? – Snowball Apr 4 at 4:37

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.