I'm trying to edit the tag.php page so that it displays all tagged posts (as it normally does) 'but' I want to call a function after the 3rd post in the loop.

Current Code

<?php /* The loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
    <?php get_template_part( 'content', get_post_format() ); ?>
<?php endwhile; ?>

Any suggestions on how to insert the following function after the 3rd post in the loop?

<?php echo someFunction() ?>

You can make use of the build in loop counter, $current_post which you can access in the main query with $wp_query->current_post. (Just a note, the counter starts at 0, so post 1 will be 0)

The main query uses WP_Query, $wp_query being the query variable used, so have a look at the Methods and Properties which you can make use of and the uses of these Methods and Properties

Inside your loop, just before endwhile, add the following

if( 2 === $wp_query->current_post ) {
    echo someFunction();
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.