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?
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:
Nice question. A possible solution below, however not exactly elegant because it requires you to have a fixed number of shortcodes on each page, e.g. 4:
If you need to just count the total tags in a page/post you can use this:
It is happens, because on every page load you redefined your function, so
static $i=1;
will executed always.Maybe you want to use a
$_SESSION
variable. But do not forget thesession_start()
somewhere ininit
callback.Setting the session, put it into the
functions.php