shortcode – wpv-counter

Sometimes it is useful to have an incremental counter to assign a unique and ordered number to each post in the loop. It is possible to use it to display the post number in the output or as a variable inside the loop, for example, to associate a specific css class to any post.

I can add this shortcode:

// Counter shortcode

add_shortcode( 'wpv-counter', 'counter_shortcode' );
function counter_shortcode() {
  static $counter = 0;
  $counter ++;
  return $counter;

Then I can use this shortcode in the post loop to return the index value:


The shortcode will increment +1 every time it is displayed. The only limitation is that it is not possible to display more then one counter on each post, because it will increment +1 every time.

chrisH-10 offered an improved version of the shortcode with a name and a start attribute:

// Improved counter shortcode

add_shortcode( 'wpv-counter', 'counter_shortcode' );
function counter_shortcode($atts = []) {
    $atts = array_change_key_case((array)$atts, CASE_LOWER);
    $atts = shortcode_atts(['name' => 'default', 'start' => 1], $atts);
    $name = $atts['name'];
    static $counter = array();
    $counter[$name] = ($counter[$name]) ? $counter[$name]+1 : $atts['start'];
    return $counter[$name];

In this case it is possible to add more then one counter for each post with this shortcode:

[wpv-counter name='counter1' start='1']
[wpv-counter name='shortcode-wpv-counter' start='1']

You can find this solution on this Toolset forum thread:

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>