Skip Navigation

[Resolved] Loop number

This thread is resolved. Here is a description of the problem and solution.

Problem:
How to output the current loop iteration?

Solution:
You'll need to register a custom shortcode for this.

An example of a general purpose shortcode suitable for this is given below: https://toolset.com/forums/topic/loop-number/#post-1069106

This support ticket is created 6 years, 6 months ago. There's a good chance that you are reading advice that it now obsolete.

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.

Sun Mon Tue Wed Thu Fri Sat
- 7:00 – 14:00 7:00 – 14:00 7:00 – 14:00 7:00 – 14:00 7:00 – 14:00 -
- 15:00 – 16:00 15:00 – 16:00 15:00 – 16:00 15:00 – 16:00 15:00 – 16:00 -

Supporter timezone: Europe/London (GMT+00:00)

Tagged: 

This topic contains 2 replies, has 2 voices.

Last updated by randallH-3 6 years, 6 months ago.

Assisted by: Nigel.

Author
Posts
#1056436

How can I output the loop number of items in a table?

Table
Number | Title
1 | Title 1
2 | Title 2
3 | Title 3

#1069106

Nigel
Supporter

Languages: English (English ) Spanish (Español )

Timezone: Europe/London (GMT+00:00)

Hi Randy

I have a custom shortcode that you can register for this:

/**
 * Add loop-iteration shortcode
 * 
 * Attributes
 * 'n' (optional) : test for nth iteration
 */
add_shortcode( 'loop-iteration', function( $atts ){

	global $loop_n;

	if ( !isset( $loop_n ) ) {
		$loop_n = 0;
		return $loop_n;
	}

	$loop_n++;

	if ( !isset( $atts['n'] ) ) {
		// no nth parameter, just return the current index
		return $loop_n;
	}
	else {
		$remainder = ( $loop_n + 1 ) % $atts['n'];
		return ( $remainder == 0 );
	}

});

It's a general purpose shortcode that can be used one of two ways.

Without any attributes it will simply output the current loop iteration.

With an 'n' parameter you can also use it inside conditional shortcodes to only show something every nth iteration, e.g.

[wpv-conditional if="( '[loop-iteration n='3']' eq '1' )"]
  <p>3rd item in loop</p>
[/wpv-conditional]
#1069112

Thank you.