I need to wrap every 4 Wordpress posts in a div

I need a div to wrap every four columns in a wordpress chain. So that would be like

<div>
four posts
</div>
<div>
four posts
</div>

my current code is

<?php 
        $i = 0;
        $wrap_div = "<div class='frak'>";
            if ( have_posts() ) {
               echo $wrap_div;
                while ( have_posts() ) {
                    the_post();

        ?>

        <div class="wine-section">
            <?php the_post_thumbnail(); ?>
            <div class="wine-info">
                <a href="<?php the_permalink(); ?>"><?php the_title( '<h1>', '</h1>' ); ?></a>
                <?php the_meta(); ?>
            </div><!-- /wine-info -->
            <div class="c"></div>
        </div><!-- /wine-section -->

        <?php       
                if ($i % 4 == 0) { echo "</div>" . $wrap_div; }
                } // end while
            } // end if
            $i++;
        ?>

This code wraps each entry individually. Any ideas?

+1
source share
2 answers

You are increasing $ioutside the cycle while, so $ithere will always be inside ==0and therefore $i % 4 == 0.

Move $i++;to } // end while.

However, you must also change your condition to $i % 4 == 3, because it $i % 4 == 0evaluates truein the very first iteration ( $i=0) and creates an initial <div>one with only one message.

, :

  • $i=1 0

  • $i++ while.

, 4 , , <div>. , , , a <div> , . .

, $i % 4 == 3 , echo '</div>'; while, if(($i % 4 == 3)&& have_posts()).

0

- . 0 % 4 == 0 true - , 0 4, 0. , .

, , , , 12, div "frak" .

<?php 
    $i = 0;
    $wrap_div = "<div class='frak'>";
        if ( have_posts() ) {
            // Grab the total posts that are being displayed
            $total_posts = $wp_query->post_count;
            echo $wrap_div;
            while ( have_posts() ) {
                the_post(); ?>
                <div class="wine-section">
                    <?php the_post_thumbnail(); ?>
                    <div class="wine-info">
                        <a href="<?php the_permalink(); ?>"><?php the_title( '<h1>', '</h1>' ); ?></a>
                        <?php the_meta(); ?>
                    </div><!-- /wine-info -->
                    <div class="c"></div>
                </div><!-- /wine-section -->
                <?php 
                // Is this a fourth post? If so, make sure it is not the last post?
                if ( $i % 4 == 0 && $i != 0 && ( $i + 1 ) != $total_posts ) {
                    echo '</div>' . $wrap_div;
                }
                $i ++;
            } // end while
            // Close the $wrap_div
            echo '</div>';
        } // end if
?>

if, , . , $i 0 ( , ), $i + 1 ( while()).

, while() - , 4 ( ) - div while - .

+1

Source: https://habr.com/ru/post/1657172/


All Articles