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.
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
Thanks Adriano,
That's really helpful and I'm sure that'll sort my problem out.
Glad to help. You are welcome.
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];
}
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].