0Day Forums
Wordpress loop : get current post count inside The Loop - Printable Version

+- 0Day Forums (https://zeroday.vip)
+-- Forum: Coding (https://zeroday.vip/Forum-Coding)
+--- Forum: CMS (https://zeroday.vip/Forum-CMS)
+---- Forum: WordPress (https://zeroday.vip/Forum-WordPress)
+---- Thread: Wordpress loop : get current post count inside The Loop (/Thread-Wordpress-loop-get-current-post-count-inside-The-Loop)



Wordpress loop : get current post count inside The Loop - jenellejenesia375 - 07-27-2023

When inside The Loop, I want to retrieve the current post count.

For example, after every 3 posts, I want to insert an ad.

So, how do I get the value of the loop count?


RE: Wordpress loop : get current post count inside The Loop - pedagogicsk - 07-27-2023

Why not incrementing a variable then display your ads when needed?

while(LOOP)
echo $i%3==0 ? $ad : '';
$i++


RE: Wordpress loop : get current post count inside The Loop - wilsonigxtmj - 07-27-2023

Unsure why, but the suggested methods didn't work out for me, I had to resort to the following

$loop_counter = 1;
while( $query->have_posts() )
{
//Do your thing $query->the_post(); etc

$loop_counter++;
}

Safer than playing with globals if you ask me.


RE: Wordpress loop : get current post count inside The Loop - daryncenmxdpux - 07-27-2023

You can use the `current_post` member of the [`WP_Query`][1] object instance to get the current post iteration;

while ( have_posts() ) : the_post();

// your normal post code

if ( ( $wp_query->current_post + 1 ) % 3 === 0 ) {

// your ad code here

}

endwhile;

Note, if you're using this inside a function, you'll need to globalise `$wp_query`.
[1]:

[To see links please register here]