WordPress.org

Ready to get started?Download WordPress

Forums

Wrap every 4 iterations with an active class on the very first item (5 posts)

  1. idvisionstudio
    Member
    Posted 7 months ago #

    Hi everyone!
    I'm using the bootstrap 3 framework and I've implemented an horizontal carousel which displays 4 items at a time. So we have 4 items wrapped in a container and when we click on left or right it display 4 new items. The problem for me is that in order to get it works, the first wrapping container must have an "active" class. This is where I block. Take a look at the following code that's working fine, I mean I can see the loop working fine with the Chrome inspector but nothing will display until I had the class "active" to the very first container :

    <?php
        $count = 0;
        query_posts('cat=4');
        if(have_posts()) : while(have_posts()) : the_post();
    
            $open = !($count%4) ? '<div class="item"><ul class="row list-unstyled">' : '';
            $close = !($count%4) && $count ? '</ul></div>' : '';
    
            echo $close.$open;
        ?>
        <li class="col-sm-3"><a href="#"><img class="img-responsive" src="http://placehold.it/313x250" alt="Image"></a></li>
        <?php
        $count++;
        endwhile;
        endif;
        echo $count ? '</ul></div>' : '';
        ?>

    The class needs to be added in the $open var next to the class "item" of the opening div.

    Any idea?

  2. alchymyth
    The Sweeper & Moderator
    Posted 7 months ago #

    (not tested)

    $open = !($count%4) ? '<div class="item' . ( $count == 0 ? ' active' : '' ) . '"><ul class="row list-unstyled">' : '';

  3. idvisionstudio
    Member
    Posted 7 months ago #

    Hi alchymyth and thank you to answer me!
    Is it good to imbricate 2 ternary conditionals? The ternary conditionals are often criticized to be greedy but 2 I wonder if that's a right method. What do you think?

  4. alchymyth
    The Sweeper & Moderator
    Posted 7 months ago #

    Is it good to imbricate 2 ternary conditionals?

    I can't tell -
    however, there are other ways, if you don't want to wrap the ternary conditions; for example:

    $active = $count == 0 ? ' active' : '';
            $open = !($count%4) ? '<div class="item' . $active . '"><ul class="row list-unstyled">' : '';
  5. idvisionstudio
    Member
    Posted 7 months ago #

    I've tried something similar but it seems that ternary conditionals don't really this too. Anyway I'll give it a try, who knows it might work this time. Thanks I keep you in touch.

Reply

You must log in to post.

About this Topic