2014-01-28 66 views
1

我有一個WordPress主題,我有一個情況,在主循環模板(index.php)我需要一些時間運行自定義循環。所以它看起來像這樣:有沒有辦法在不重複代碼的情況下運行這兩個循環?

$the_qry = new WP_Query(array('post_type' => 'post', 'offset' => 4, 'orderby' => 'date', 'order' => 'DESC', 'post_status' => 'publish', 'paged' => $paged)); 

if ($the_qry->have_posts()) : while ($the_qry->have_posts()) : $the_qry->the_post(); 

,但我需要它運行正常

if (have_posts()) : while (have_posts()) : the_post();

我試着包裝他們在IF這樣的其他情況:

if ($special_situation == true) { 
     if ($the_qry->have_posts()) : while ($the_qry->have_posts()) : $the_qry->the_post(); 
    } else { 
     if (have_posts()) : while (have_posts()) : the_post(); 
    } 
    // output each post code 
    endwhile; endif; 

但它當然不起作用,因爲IF沒有在IF語句中關閉,所以它不會以這種方式工作。我能想到的唯一的解決辦法是要做到這一點:

if ($special_situation == true) { 
     if ($the_qry->have_posts()) : while ($the_qry->have_posts()) : $the_qry->the_post(); 
     // output each post code 
     endwhile; endif; 
    } else { 
     if (have_posts()) : while (have_posts()) : the_post(); 
     // output each post code 
     endwhile; endif; 
    } 

但似乎愚蠢的,我因爲// output each post code不會改變,所以我重複了很多代碼。

有沒有辦法簡化這一切?

謝謝!

+0

爲什麼不把'每個郵政編碼'輸出到函數中並在每個地方調用該函數? –

+0

我也考慮過,但我希望我可以將它全部保留在一個文件中,並簡單地操作if/while/the_post()部分。 – user3245789

回答

0
global $wp_query; 
if($special_situation == true){ 
    $the_qry = new WP_Query(array('post_type' => 'post', 'offset' => 4, 'orderby' => 'date', 'order' => 'DESC', 'post_status' => 'publish', 'paged' => $paged)); 
} 
else{ 
    $the_qry = $wp_query; //Sets $the_qry to default query 
} 
if ($the_qry->have_posts()) : while ($the_qry->have_posts()) : $the_qry->the_post(); 
    // output each post code 
endwhile; endif; 
+0

我看到了你的第一次提交,我用它得到了和上次編輯幾乎相同的結果。唯一的區別是我把全局移到了else {}部分,因爲除非特殊假設是錯誤的,否則不需要它。感謝您的幫助 – user3245789

+0

是的,我最初誤解了這個問題。對於那個很抱歉。很高興它指出你在正確的方向,但! – maiorano84

相關問題