【问题标题】:Foreach & While Producing Duplicate OutputForeach 和同时产生重复输出
【发布时间】:2013-10-02 15:41:30
【问题描述】:

我仍在努力学习 PHP,我已经在这段代码上花费了大量时间,并且快到了我需要的地方。基本上,该代码旨在抓取过去 10 天的 WP 帖子,随机选择两个,然后显示帖子中的第一张图片并链接到该帖子。还应该将第一个图像设置为 .second 类,将第二个图像设置为 .third 类。不幸的是,它在某种程度上可以工作,但会不断产生相同图像的重复副本。该数组似乎正在工作,除了我只需要每个图像的一个副本。这是代码,减去日期过滤器和 catch_that_image() 函数,它们都工作正常:

add_filter( 'posts_where', 'filter_where' );

$banner_class = array('second','third');
$the_query = new WP_Query( array('orderby' => 'rand', 'posts_per_page' => '2' ));

while ( $the_query->have_posts() ) : $the_query->the_post();
if (!empty($the_query)) {
foreach ($banner_class as $value){ ?>
<div class="banner small image <?php echo $value; ?>" >
<?php echo '<a href="'. get_permalink().'">'; ?>
<img src="<?php echo catch_that_image(); ?>" width="300px"> 
<?php echo '</a></div>';
}
}

endwhile;


remove_filter( 'posts_where', 'filter_where' );

我确信这是一个简单的解决方案,毫无疑问,这与同时使用 while 和 foreach 有关。这是输出:http://www.mymusicisbetterthanyours.com/slider-test/

非常感谢任何帮助!

【问题讨论】:

    标签: php wordpress foreach while-loop


    【解决方案1】:
    $n = 0;
    while ( $the_query->have_posts() ) : $the_query->the_post();
    ?>
        <div class="banner small image <?php echo $banner_class[$n]; ?>">
            <a href="<?php the_permalink(); ?>"><img src="<?php echo catch_that_image(); ?>" width="300px"></a>
        </div> 
    <?php $n ++; endwhile; ?>
    

    在实际循环中去掉那个 foreach 循环。您以这种方式在每次迭代中编写 html 两次。为横幅类添加一个基本计数器。在这种情况下 $n,然后在 post 循环的每次迭代中递增它。

    顺便说一句,我简化了你的输出。您无需检查查询是否为空。这就是 while 条件正在做的事情。闯入和退出php来编写html部分没有意义。我在您的查询中也没有看到任何内容可以保证随机帖子仅限于过去 10 天。

    【讨论】:

    • 哇。惊人的。非常感谢您的及时回复!帖子的过滤器在其他地方(functions.php),但它工作得很好,所以我想我不需要包含它。我显然还有很多东西要学,但这很有帮助!
    猜你喜欢
    • 2017-09-11
    • 2018-05-11
    • 2022-01-12
    • 2013-05-18
    • 1970-01-01
    • 2023-01-14
    • 2017-02-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多