0

I'm creating a grid of columns and need to add a css class to each column at the end of the loop based on the amount of posts returned so it returns something like this:

<div class="column-3"</div>
<div class="column-3"</div>
<div class="column-3"</div>

ANSWER

Use $loop->found-posts()!

  <div class="airport-children">
    <?php
      $args = array( 'post_parent' => wp_get_post_parent_id( $post_ID ), 'post_type' => 'airports', 'posts_per_page' => -1 );
      $loop = new WP_Query( $args );
      while ( $loop->have_posts() ) : $loop->the_post();
    ?>
    <div class="airport-child column-<?php echo $loop->found_posts ?>">
      <h2><?php the_title(); ?></h2>
      <a href="<?php echo the_permalink(); ?>"><button>View</button></a>
    </div>

    <?php endwhile;  wp_reset_postdata(); ?>
  </div>
  • sidenote: not sure what CSS you are using for spacing but I have just switched my own column grid to use an inner padding divs inside each column rather than outer column margins, as you can't know the number of blocks/spacers that will used when setting the column widths, but with inner padding you don't have to. just thought i'd share. – majick Apr 6 '16 at 10:55
  • Ah yeah good idea, will use padding and not margins on my columns! Thanks :) – Thomas_Hoadley Apr 6 '16 at 11:06
2

If I understood this issue correctly the problem with your current code is that you are incrementing $totalPosts variable inside the while loop, so the variable gets incremented after every post thus resulting in the running order you described.

To get the amount of posts returned matching the query, use $loop->found_posts (in this case)

More information, examples and documentation about the WP_Querycan be found from WordPress Codex

  • 1
    @Thomas_Hoadley I understood your question differently, so I must ask: Will this solution also work for you if you have 10 posts and not just 3? – Phaze Phusion Apr 6 '16 at 9:56
  • Yeah it does indeed! It literally just gets the total amount of posts in the current loop, so if there were 10 posts it would echo out 10 as the class name. – Thomas_Hoadley Apr 6 '16 at 10:00

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.