2013-03-26 43 views
0

我嘗試使用下面的代碼的輸出是一個日期大於或等於今天的日期的事件列表:設置循環之前在循環外設置變量的最佳方法是什麼?

$args = array('post_type' => 'event') // setup my custom post type  
$todaysdate = blah blah //setup for today's date 

// the wp loop 
query_posts($args); 

if ((have_posts() && $eventdate >= $todaysdate) ) : while (have_posts()) : the_post(); 

$eventdate = blah blah // setup for the date of the event; 

echo $event; 

endwhile; endif; 

正如你所看到的問題是,如果依賴於在循環內的變量。

首先在循環外設置變量的最佳方法是什麼?

+1

爲什麼不直接運行while循環並將if語句移到while循環中? – Jonast92 2013-03-26 16:24:46

回答

0

那如果實際上應該是內循環,像

$args = array('post_type' => 'event') // setup my custom post type  
$todaysdate = "blah blah"; //setup for today's date 

// the wp loop 
query_posts($args); 

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

$eventdate = "blah blah"; // setup for the date of the event; 

if($eventdate >= $todaysdate)) 

echo $event; 

endif; 

endwhile; endif; 

編輯:

Thanks, this works fine, however, I want to output a set number of events (5 in total) which I've defined in $args. So $args sets up 5 events, but the second IF then filters out old events so I end up with less than 5.

但是,這是你有同樣的原因,如果排在首位。但是,如果您的意思是它應該顯示5個事件後,那麼wp_query本身需要修改。請參閱Examples Here

+0

謝謝,這工作正常,但是,我想輸出一組事件(總共5個)已經在$ args中定義了。所以$ args設置了5個事件,但第二個IF然後過濾掉了舊事件,所以我最終得到的結果少於5個。 – user18577 2013-03-26 16:35:53

+0

檢查更新的答案 – 2013-03-26 16:39:39

+0

非常感謝。我使用$ query = new WP_Query(array('meta_key'=>'mydate','meta_value'=> $ todaysdate,'meta_compare'=>'> ='))修復了它。 – user18577 2013-03-26 17:09:47

0

而不是做

if stuff from while iteration that doesn't exist yet 
    while 

那麼你應該做的

while 
    if stuff from current while iteration 

像你說:「正如你所看到的問題是,如果依賴於一個變量,它是內循環。」

您只需構造您的代碼,以便在您當前執行的時候需要什麼。只需將依賴關係移動到適當位置,以便在使用它之前就存在。

+0

謝謝。我試圖在WHILE中移動IF,但得到'致命錯誤:超過30秒的最大執行時間' – user18577 2013-03-26 16:38:40