每三个图像PHP后添加一个新行

时间:2017-05-22 09:42:13

标签: php html css wordpress advanced-custom-fields

我使用WordPress中的高级自定义字段创建了一个图库。现在我需要添加一个if语句,它将回显一个新div,并在每三个图像后用行类关闭它。我试图自己做,但它不起作用。我哪里错了?

<div class="container">
    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
        <?php the_content(); ?>
        <?php endwhile; else: ?>
        <p>No Content</p>
    <?php endif; ?>

    <?php 
        $images = get_field('gallery_images');
        $counter = 3;
    ?>

    <ul class="gal_list">
        <?php foreach( $images as $image ): ?>

        <?php 
            if($counter == 3){
                echo "<div class="row">";
                $counter = 0;
            }
        ?>

            <li class="col-md-4">
                <a class="img-responsive" href="<?php echo $image['url']; ?>" rel="<?php the_title() ?>"><img src="<?php echo $image['sizes']['thumbnail']; ?>" alt="<?php echo $image['alt']; ?>" /></a>
            </li>

            <?php 
                if($counter == 0){
                    echo "</div>";
                }
                $counter++;
            ?>
        <?php endforeach; ?>
    </ul>
</div> 

2 个答案:

答案 0 :(得分:1)

您需要转义引号,因为您使用的是"

更改:

echo "<div class="row">";

要:

echo "<div class=\"row\">";

答案 1 :(得分:0)

<div class="container">
    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
        <?php the_content(); ?>
        <?php endwhile; else: ?>
        <p>No Content</p>
    <?php endif; ?>

    <?php 
        $images = get_field('gallery_images');
        $counter = 3;
    ?>

    <?php foreach( $images as $image ): ?>

    <!--add a new row after every three images-->
    <?php 
        if($counter == 3){
            echo "<ul class=\"row gal_list\">";
        }
    ?>

    <li class="col-md-4">
        <a class="img-responsive" href="<?php echo $image['url']; ?>" rel="<?php the_title() ?>"><img src="<?php echo $image['sizes']['thumbnail']; ?>" alt="<?php echo $image['alt']; ?>" /></a>
    </li>

    <!--close the row after three images, also decrement the counter and reset-->
    <?php 
        $counter--;
        if($counter == 0){
            echo "</ul>";
            $counter = 3;
        }
    ?>
    <?php endforeach; ?>
</div> 

我的代码好吗?