Support » Developing with WordPress » Count how many times shortcode is called and display different content in each

  • Resolved brveljkovic

    (@brveljkovic)


    I am calling out shortcode several times on the page.
    Some Text
    [shortcode][/shortcode]
    More text
    [shortcode][/shortcode]
    I would like to count how many times the shortcode is called out before it renders as html and then display different output.
    Outputs are being loaded from settings page.
    not sure if I described the problem correctly, it a very unusual request

Viewing 4 replies - 1 through 4 (of 4 total)
  • this turned out to be fairll simple at the end. Just added indicator
    <?php
    $options = get_option( ‘cmby_settings’ );
    // Output Shortcode
    function cmby_list_widgets($atts, $content = null){
    static $i=0;
    $atts = shortcode_atts(array(
    ‘title’ => ‘Cambrick Yard Widgets’,
    ‘special’ => $ran
    ), $atts);
    global $options;
    $output = ‘<div class=”widgetcontainer”>’;
    $output .= ‘<div class=”widgetblock”>’;
    $output .= $options[“cmby_textarea_field_$i”].'<br/></div>’;
    $i++;
    return $output;

    }

    add_shortcode(‘cambrickyardwidgets’, ‘cmby_list_widgets’);

    Moderator keesiemeijer

    (@keesiemeijer)

    moderator

    Hi brveljkovic

    Does it matter if the shortcodes are in one post, or from multiple posts in a page?

    To count the shortcodes being output you can add a static counter to your shortcode
    http://php.net/manual/en/language.variables.scope.php#language.variables.scope.static

    Here’s an example shortcode

    
    function my_content_shortcode( $atts, $content = null ) {
    	static $count = 0;
    	$count++;
    
    	return '<span class="shortcode-count">My Shortcode ' . $count . '</span>';
    }
    add_shortcode( 'my_content', 'my_content_shortcode' );
    Moderator keesiemeijer

    (@keesiemeijer)

    moderator

    Haha, you beat me by 20 seconds!

    Glad you’ve solved it

    thanks anyway!

Viewing 4 replies - 1 through 4 (of 4 total)
  • You must be logged in to reply to this topic.