Search code examples
phpwordpressshortcode

Count the number of times a WordPress shortcode is used in a post


I have the following WordPress shortcode function:

function wp_shortcode() {
 static $i=1;
 $return = '['.$i.']';
 $i++;
 return $return;
}
add_shortcode('shortcode', 'wp_shortcode');

This works fine. The $i variable gets incremented each time the function is called in the article. So for

[shortcode][shortcode][shortcode][shortcode]

the output is as expected

[1][2][3][4]

but

if the article has more than one page, than the counter resets on the next article page. So for:

[shortcode][shortcode][shortcode][shortcode]
<!--nextpage-->
[shortcode][shortcode][shortcode][shortcode]

the output is

[1][2][3][4]
<!--nextpage-->
[1][2][3][4]

instead of the wanted output of:

[1][2][3][4]
<!--nextpage-->
[5][6][7][8]

Anyway to change this?


Solution

  • So after researching a bit more @diggy's idea with pre processing the_content and adding the $atts to the shorcodes before the shortcodes are rendered, I came up with this:

    function my_shortcode_content( $content ) {
     //check to see if the post has your shortcode, skip do nothing if not found
     if( has_shortcode( $content, 'shortcode' ) ):
    
      //replace any shortcodes to the basic form ([shortcode 1] back to [shortcode])
      //usefull when the post is edited and more shortcodes are added
      $content = preg_replace('/shortcode .]/', 'shortcode]', $content);
    
      //loop the content and replace the basic shortcodes with the incremented value
      $content = preg_replace_callback('/shortocode]/', 'rep_count', $content);
    
     endif;
    
    return $content;
    }
    add_filter( 'content_save_pre' , 'my_shortcode_content' , 10, 1);
    
    function rep_count($matches) {
     static $i = 1;
    return 'shortcode ' . $i++ .']';
    }