Owl Carousel two rows issue

Im using Owl Carousel with WordPress and it’s loading dynamic content with the help of a WP loop.
Here is the loop code:

<?php
    $args = array(
        'post_type' => 'properties',
        'posts_per_page' => -1,
        'paged' => $paged
    );

    $the_query = new WP_Query($args);
?>

<?php
    $i = 1;
    //added before to ensure it gets opened
    echo '<div class="item-wrapper">';
    if (have_posts()):
        while ($the_query->have_posts()):
            $the_query->the_post();
?>  

<div class="item">
    <img class="img-responsive img-rounded" src="<?php the_field('property_foto');?>" alt="AWF Property Example" />
</div>

<?php
            if ($i % 2 == 0) {
                echo '</div><div class="item-wrapper">';
            } // if multiple of 3 close div and open a new div
            $i++;
        endwhile;
    endif;
    //make sure open div is closed
    echo '</div>';
?>

and my JS for the Carousel:

Read More
$(document).ready(function(){
    $("#owl-properties").owlCarousel({
        nav: true,
        pagination: true,
        loop: true,
        dots: false,
        autoplay: false,
        autoplayTimeout:2000,
        autoplayHoverPause:true,
        navText: [
              "<span class='glyphicon glyphicon-chevron-left'></span>",
              "<span class='glyphicon glyphicon-chevron-right'></span>"
          ],
        margin:10,
        responsiveClass:true,
        responsive:{
            0:{
                items:2,
            },
            450:{
                items:3,
            },
            767:{
                items:4,
            },
            991:{
                items:5,
            },
            1199:{
                items:5,
            }
        } 
    });
});

I’ve added some code to the loop in order to echo div’s every two items, this way I create two rows. However, at the end of all the items, it spits out an empty <div class="item-wrapper"></div> which causes to display an empty column without any images.

What is wrong in my code? Would be great if anybody could help me out!

Thanks!

Related posts

Leave a Reply

1 comment

  1. You need to also do a check for if it’s the last post and if it is omit the adding of echo '</div><div class="item-wrapper">';

    Something like this:

    if ($i % 2 == 0 && ($the_query->found_posts != $i)) {
        echo '</div><div class="item-wrapper">';
    } // if multiple of 3 close div and open a new div