【发布时间】: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