Been hitting a nail with this one as i'm very amateur with php. I have a loop in tag.php but it shows all posts with that tag - how can I limit the number to say, 5?

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    <h2 align="center">  <a href="<?php echo get_permalink() ?>"> <?php the_title(); ?>  </a> </h2>
    <?php the_content(); ?>
    <?php endwhile; else: ?>
    <p>Sorry, no posts we're found.</p>
    <?php endif; ?>
<?php wp_reset_query(); ?>

  • wp_reset_query should only be used to clean up after query_posts calls. Since you should never use query_posts it follows that you should never use wp_reset_query. Burn it from your code with the fire of a thousand suns – Tom J Nowell Feb 14 at 12:42
  • are you using query_posts? – Tom J Nowell Feb 14 at 14:16

If you want to modify the main post query, use the pre_get_posts filter:

add_action( 'pre_get_posts', 'limit_tags_to_196_posts' );
function limit_tags_to_196_posts( \WP_Query $query ) {
    // we only want tag archives
    if ( is_admin() || ! $query->is_main_query() || ! $query->is_tag() ) {
    $query->set( 'posts_per_page', 196 );

Notice that we check the query first, we don't want to change all queries everywhere or we'll be changing WP Admin or RSS feeds, etc, we only want tag archives

  • Thank you. Placed this code in functions.php, and also did a small change to test it (196 to 3) but I still get all posts within the tag. – beluoso Feb 14 at 13:23
  • 1
    @beluoso re: my original comment on your question, are you use query_posts but didn't include it in your question? Is your main loop for the main query? This is super important – Tom J Nowell Feb 14 at 14:16

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.