1

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?

2

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++;

    }

}
  • 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 '16 at 4:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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