2013-09-26 31 views
0

我仍然在努力提取PHP,並且我在這段代碼上花了很多時間,並且幾乎到了我需要的地方。基本上,代碼旨在抓取過去10天的WP帖子,隨機挑選兩個帖子,然後在帖子中顯示第一張圖片並鏈接到該帖子。它也應該設置第一個圖像的類。第二個和第二個與類.third。不幸的是,它在某種程度上工作,但不斷製作相同圖像的重複副本。該陣列似乎工作,除了我只需要每個圖像少一個副本。下面的代碼,減去日期過濾器和catch_that_image()函數,這兩者都是做工精細:Foreach&While生成重複輸出

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'); 

我敢肯定,這是一個簡單的解決方案,無疑是有事情做與同時和foreach使用一起。這裏輸出:http://www.mymusicisbetterthanyours.com/slider-test/

任何幫助非常感謝!

回答

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,然後在每個迭代後循環中增加它。

順便說一下,我簡化了你的輸出。您不需要檢查查詢是否爲空。這就是條件正在做的事情。打破和出來的PHP寫段的HTML沒有意義。我的查詢中也沒有看到保證隨機帖子被限制在過去10天內的任何內容。

+0

哇。驚人。真的很感激迅速的迴應!該職位的過濾器是其他地方(functions.php),但工作得很好,所以我想我不需要包括它。我仍然有很多東西需要學習,但是這對我們有很大幫助! – brianjohnhanna