【问题标题】:Reset counter after each post loop在每个后循环后重置计数器
【发布时间】:2020-03-24 07:40:48
【问题描述】:

我在自定义 post 类型循环内有一个 ACF 中继器,该循环带有一个计数器,每两个 col-md-6 围绕一行。当我有偶数个 col 时,这很有效,但当它不均匀时就不行了。当一篇文章的列数不均匀时,计数器会以某种方式记住下一篇文章,并且只在第一行显示一个列。

在这里,您将找到当前代码和正在发生的事情的小图片。 不知何故,我需要在每次发布循环后重置计数器,但无法弄清楚。 wp_reset_postdata 似乎不起作用。

<?php $args = array( 'post_type' => 'posttypename', 'posts_per_page' => '-1' ); $the_query = new WP_Query( $args ); ?>
<?php if ( $the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

<div>
    <div class="container">

        <div class="row">

            <div class="col-md-12">
                <h1><?php the_title(); ?></h1>
            </div>

        </div>

        <?php if( have_rows('row') ): ?>
            <div class="row">
            <?php while( have_rows('row') ): the_row(); $text = get_sub_field('text'); ?>

                <div class="col-md-6">      
                    <?php echo $text; ?>
                </div>

                <?php $counter++; if($counter % 2 === 0) :  echo '</div> <div class="row">'; endif; ?>
            <?php endwhile; ?>
            </div>
        <?php endif; ?>

    </div>
</div>

<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php endif; ?>

【问题讨论】:

    标签: php wordpress loops counter advanced-custom-fields


    【解决方案1】:

    只是一个小小的改变。您需要确保在 acf 的循环开始之前将您的计数器重置为 0。

            <?php $counter = 0; //Initialize your Counter here before the Loop Starts for each Post ?> 
            <?php if( have_rows('row') ): ?>
                <div class="row">
                <?php while( have_rows('row') ): the_row(); $text = get_sub_field('text'); ?>
    
                    <div class="col-md-6">      
                        <?php echo $text; ?>
                    </div>
    
                    <?php $counter++; if($counter % 2 === 0) :  echo '</div> <div class="row">'; endif; ?>
                <?php endwhile; ?>
                </div>
            <?php endif; ?>
    

    【讨论】:

      猜你喜欢
      • 2011-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多