Forums

Auto-Increment a Variable Each Time a Shortcode is Called (4 posts)

  1. mhoiland
    Member
    Posted 1 year ago #

    Hello,

    I'm writing a plugin that requires a unique identifier if a post contains more than one instance of the shortcode.

    Here's a shortcode function for example:

    function foo() {
    	$i = 0;
    	$i++;
    	return $i;
    	}
    add_shortcode('foo','foo');

    If I enter the shortcode twice in a post like this...

    [foo]
    [foo]

    it will return this...

    1 1

    But I would like it to return...

    1 2

    Any ideas?

  2. mhoiland
    Member
    Posted 1 year ago #

    Nobody with mad shortcode skills?

  3. alchymyth
    The Sweeper
    Posted 1 year ago #

    not sure if it will work, but look into 'static' php variables:
    http://www.tutorialspoint.com/php/php_static_variables.htm

  4. mhoiland
    Member
    Posted 1 year ago #

    Brilliant! Works perfectly.

    function foo() {
    	STATIC $i = 0;
    	$i++;
    	return $i;
    	}
    add_shortcode('foo','foo');

Topic Closed

This topic has been closed to new replies.

About this Topic