Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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
add comment

1 Answer 1

up vote 1 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
      self::$instance++;

    }

}
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
add comment

Your Answer

 
discard

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.