How to check if this is the nth instance of a given shortcode in a post

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?

Read More

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?

Related posts

Leave a Reply

1 comment

  1. 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++;
    
        }
    
    }