Support » Plugins » How to count number of instances of a shortcode

  • Phil Kurth


    Hi Guys

    I’m currently working on a class that will allow my users to create columns with very simple shortcodes. No attributes, no closing tags, just the name of the code. I’m using the twitter bootstrap framework and all works well, provided the number of columns is fixed.

    What I want to do, is count up the number of times the [column] shortcode appears in the post before the shortcode outputs its HTML. I need to do this so I can divide the width of the row container by the number of columns.

    I have tried using a count variable in the class but the shortcodes obviously execute as they are counted, leaving me short of the total number of instances.

    Here is the code as it would be used by a user…
    users content
    users content
    users content
    [finish columns]

    Here is the class I am working with. The output is only text at the moment so I can see what is happening with the logic.

    new customShortCodes();
    class customShortCodes
        private $count       = 1;
        private $instance    = array();
        private $span        = 12;
        function __construct(){
            add_shortcode( 'column', array($this, 'column'));
            add_shortcode( 'finish columns', array($this, 'finish_columns'));
        function column(){
            array_push( $this->instance, $this->count );
            if( $this->count == 1 ){
                $html = 'ROW BLOCK'.$this->span;
                $html = 'endBLOCK BLOCK'.$this->span;
            return $html;
        function finish_columns(){
            $this->span = $this->span / count( $this->instance );
            return 'endBLOCK endROW';

    Any help on this would be incredible.


  • The topic ‘How to count number of instances of a shortcode’ is closed to new replies.