2013-03-26 29 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

相关问题