Skip Navigation

[Resolved] Shortcode for the index of a repeater

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

This topic contains 5 replies, has 3 voices.

Last updated by chrisH-10 5 years, 7 months ago.

Assigned support staff: Adriano.

Author
Posts
#285510

Rob

I am trying to:

output a simple number of the index of the current item in a [wpv-for-each] using a shortcode, but can't find a way to do it.

So, given an example like this:

[wpv-for-each field="wpcf-category-image"]
      	
     <a data-slide-index="[I WANT THE INDEX VALUE HERE]">

              [types field="category-image" size="thumbnail" align="none"][/types]

     </a>  			

[/wpv-for-each] 

You can see that I'm trying to obtain the current index number (i.e. 0, 1, 4, 10, etc.) but can not find any ability to do this mentioned anywhere.

#285631

Hi Rob,

Unfortunately there is no native way to do that, but you can achieve something through custom shortcodes:

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

First of all you have to declare this custom shortcode in Views > Settings > "Third-party shortcode arguments". The [counter] should return the index value.

Please let me know if you are satisfied with my reply and any other questions you may have.

Regards,

Adriano Ferreira

#285638

Rob

Thanks Adriano,

That's really helpful and I'm sure that'll sort my problem out.

#285680

Glad to help. You are welcome.

#523562

Here's an improved version of that shortcode. You can call it with a name and a start attribute. The problem I had was that I was iterating over multiple views that had the [counter] and the numbers would just continue to increase.

The below will keep track of separate named counters.
You can set the start of the counter to be an arbitrary number. The default is 1.

add_shortcode( 'counter', 'counter_shortcode' );
function counter_shortcode($atts = []) {
	$atts = array_change_key_case((array)$atts, CASE_LOWER);	// normalize attribute keys, lowercase
	$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];
}
#523609

Example of calling syntax:

[counter name='counter1' start='1']
[counter name='[wpv-post-slug id="$parent"]' start='1']

The second line shows an example of using another shortcode to generate the name for the counter. In this case the slug of the parent of the item calling the [counter].