• Hi

    The following code inserts a <div class=”row thirds”> div every 3 posts. But if there are 3 posts, an empty <div class=”row thirds”> is added. How do I prevent the empty div?

    Thanks

    <div class="row thirds">
    <?php
    // Find connected pages
    $connected = new WP_Query( array(
      'connected_type' => '2-col-module_to_pages',
      'connected_items' => get_queried_object(),
      'nopaging' => true,
    ) );
    
    // Display connected pages
    if ($connected->have_posts() ) : while ($connected->have_posts()) : $connected->the_post(); ?>
    
                    <h2><?php the_title();?></h2>
    
    <?php $counter++;
    // add row div every 3 posts
          if ($counter % 3 == 0) {
             echo '</div><div class="row thirds">';
             }
            endwhile;  wp_reset_postdata(); endif; ?>
    </div>
Viewing 8 replies - 1 through 8 (of 8 total)
  • Andrew Nevins

    (@anevins)

    WCLDN 2018 Contributor | Volunteer support

    Add another conditional statement to check that counter is not equal to the length of posts.

    Thread Starter Stefan

    (@stefan83)

    Thanks for your reply, Andrew. Could you give an example please?

    Andrew Nevins

    (@anevins)

    WCLDN 2018 Contributor | Volunteer support

    Does $counter hold all of the posts? If so:

    if ($counter % 3 == 0 && $counter !== count($connected) ) {

    Thread Starter Stefan

    (@stefan83)

    So now I have this

    But it doesn’t work?

    <?php $counter++;
          if ($counter % 3 == 0) {
             echo '</div><div class="row thirds">';
             }
          if ($counter % 3 == 0 && $counter !== count($counter) ) {
            echo '';
          }
            endwhile;  wp_reset_postdata(); endif; ?>

    Am I doing something wrong?

    Andrew Nevins

    (@anevins)

    WCLDN 2018 Contributor | Volunteer support

    Sorry I meant, does $connected hold all of the posts?

    Thread Starter Stefan

    (@stefan83)

    So how does that look?

    Andrew Nevins

    (@anevins)

    WCLDN 2018 Contributor | Volunteer support

    If you var_dump $connected what do you get?

    Thread Starter Stefan

    (@stefan83)

    Sorry, I don’t know what you mean. I’m fairly new to php. Can you give a bit more detail please?

Viewing 8 replies - 1 through 8 (of 8 total)
  • The topic ‘$counter issue’ is closed to new replies.