选择开始日期小于当前日期、结束日期大于当前日期的事件

时间:2013-06-21 作者:Anas

选择开始日期小于当前日期且结束日期大于当前日期的事件

假设事件的开始日期为2013年6月12日,结束日期为2013年7月30日。我有一个查询,其中开始日期是2013-06-20,结束日期是2013-06-30。因此,事件A应该显示在我的查询结果中。但我不明白。这是我的问题

$query = "
SELECT DISTINCT ID
FROM {$wpdb->prefix}posts
JOIN {$wpdb->prefix}postmeta m1
ON ( {$wpdb->prefix}posts.ID = m1.post_id )
WHERE
{$wpdb->prefix}posts.post_type = \'tribe_events\'

AND {$wpdb->prefix}posts.post_status = \'publish\'

AND (

    ( (m1.meta_key = \'_EventStartDate\' AND m1.meta_value >= \'$start_date\') AND ( m1.meta_key = \'_EventStartDate\' AND m1.meta_value <= \'$end_date\' ))

    OR 
    ( (m1.meta_key = \'_EventEndDate\' AND m1.meta_value >= \'$start_date\') AND ( m1.meta_key = \'_EventEndDate\' AND m1.meta_value <= \'$end_date\' ) )

    OR
    ( (m1.meta_key = \'_EventStartDate\' AND m1.meta_value < \'$start_date\') AND ( m1.meta_key = \'_EventEndDate\' AND m1.meta_value > \'$end_date\') )

    )

ORDER BY {$wpdb->prefix}posts.post_date
DESC;
";

$result = $wpdb->get_results($query);
提前谢谢。

1 个回复
最合适的回答,由SO网友:birgire 整理而成

您可以尝试替换这种比较:

AND m1.meta_value >= \'$start_date\'
使用:

AND CAST(m1.meta_value AS DATE) >= \'" . date( "Y-m-d H:i:s", $start_date ) . "\'
或者,如果要对元数据使用Unix时间戳,则可以尝试:

AND m1.meta_value+0  >= ". strtotime( $start_date ) ."
更新:以下是对您的查询的修改:

$query = " SELECT DISTINCT * FROM {$wpdb->posts}
INNER JOIN {$wpdb->postmeta} m1 ON ( {$wpdb->posts}.ID = m1.post_id )
INNER JOIN {$wpdb->postmeta} m2 ON ( {$wpdb->posts}.ID = m2.post_id )
WHERE {$wpdb->posts}.post_type = \'tribe_events\'
AND {$wpdb->posts}.post_status = \'publish\'
AND (
       ( ( m1.meta_key = \'_EventStartDate\' AND CAST( m1.meta_value AS DATE ) >= %s ) AND ( m2.meta_key = \'_EventStartDate\' AND CAST( m2.meta_value AS DATE ) <= %s ))
       OR 
       ( ( m1.meta_key = \'_EventEndDate\' AND CAST( m1.meta_value AS DATE ) >= %s ) AND ( m2.meta_key = \'_EventEndDate\' AND CAST( m2.meta_value AS DATE ) <= %s ) )
       OR
       ( ( m1.meta_key = \'_EventStartDate\' AND CAST( m1.meta_value AS DATE ) < %s ) AND ( m2.meta_key = \'_EventEndDate\' AND CAST( m2.meta_value AS DATE ) > %s ) )
    )
ORDER BY {$wpdb->posts}.post_date DESC;";

$query = $wpdb->prepare( $query, $start_date, $end_date, $start_date, $end_date, $start_date, $end_date );
$result = $wpdb->get_results( $query );
这两个INNER JOINS 已添加,因为您正在使用AND 在两个不同的元键上。

结束

相关推荐

Only Showing Upcoming Events

在此页面的侧栏中:http://lifebridgecypress.org/our-people, 我有一个即将使用此代码的事件列表。。。<ul id=\"upcoming-events\"> <?php $latestPosts = new WP_Query(); $latestPosts->query(\'cat=3&showposts=10\'); ?> <?php while ($latestPos