基于自定义日期字段和时间字段的 Wordpress 查询

时间:2021-04-09 05:16:59

标签: php jquery wordpress

我正在使用 WordPress 日历插件来显示多个事件。这些事件在不同的时间在不同的日子开始。该插件工作正常并显示所有事件。

但我只想显示未来的事件。例如,如果事件在 8 月 1 日上午 11 点开始,则该事件应同时隐藏。我试图用这个查询解决我的问题:

add_filter('cmcal_calendar_posts_query', 'calendar_return_specific_events', 10, 2);

function calendar_return_specific_events($query_args, $calendar_id) {
    if ($calendar_id == 110) {
        $todays_date = current_time('d.m.Y');
        $right_now = current_time('H:i');
        $query_args = array(
            'post_type' => 'product',
            'posts_per_page' => '-1',
            'meta_query' => array(
                'relation' => 'AND',
                'date_clause' => array(
                    'key' => 'start_date',
                    'compare' => '>=',
                    'value' => $todays_date,
                ),
                'time_clause' => array(
                    'key' => 'start_time',
                    'compare' => '>=',
                    'value' => $right_now,
                ),
            ),
            'orderby' => array(
                'date_clause' => 'ASC',
                'time_clause' => 'ASC',
            )
        );
    }
    return $query_args;
}

但不幸的是它不起作用。我做错了什么?

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您应该在“meta_query”数组中设置键“type”。代码应该是这样的:

add_filter('cmcal_calendar_posts_query', 'calendar_return_specific_events', 10, 2);

function calendar_return_specific_events($query_args, $calendar_id) {
    if ($calendar_id == 110) {
        $todays_date = current_time('d.m.Y');
        $right_now = current_time('H:i');
        $query_args = array(
            'post_type' => 'product',
            'posts_per_page' => '-1',
            'meta_query' => array(
                'relation' => 'AND',
                 array(
                    'key' => 'start_date',
                    'compare' => '>=',
                    'value' => $todays_date,
                    'type' => 'DATE' //set the format
                ),
                array(
                    'key' => 'start_time',
                    'compare' => '>=',
                    'value' => $right_now,
                    'type' => 'DATE' //set the format
                ),
            ),
            'orderby' => array(
                'date_clause' => 'ASC',
                'time_clause' => 'ASC',
            )
        );
    }
    return $query_args;
}