我正在尝试按当前日期以及事件的开始和结束日期查询自定义帖子类型(事件)。我想有三个选择:现在的,即将到来的和过去的。这是我正在使用的代码,但它工作不正常。
$current = time();
switch ($print_type) {
case \'current\':
$meta_quer_args = array(
\'relation\' => \'AND\',
array(
\'key\' => \'event-start-date\',
\'value\' => $current,
\'compare\' => \'<=\',
),
array(
\'key\' => \'event-end-date\',
\'value\' => $current,
\'compare\' => \'>=\'
)
);
break;
case \'upcoming\':
$meta_quer_args = array(
\'relation\' => \'AND\',
array(
\'key\' => \'event-start-date\',
\'value\' => date(),
\'compare\' => \'>=\',
)
);
break;
case \'past\':
$meta_quer_args = array(
\'relation\' => \'AND\',
array(
\'key\' => \'event-start-date\',
\'value\' => date(),
\'compare\' => \'<\',
)
);
break;
default:
$meta_quer_args = array(
\'relation\' => \'AND\',
array(
\'key\' => \'event-end-date\',
\'value\' => date(),
\'compare\' => \'>=\',
)
);
break;
}
$query_args = array(
\'post_type\' => \'exhibitions\',
\'posts_per_page\' => -1,
\'post_status\' => \'publish\',
\'ignore_sticky_posts\' => true,
\'meta_key\' => \'event-start-date\',
\'orderby\' => \'meta_value_num\',
\'order\' => \'DESC\',
\'meta_query\' => $meta_quer_args
);
$selected_events = new WP_Query( $query_args );
SO网友:Chinmoy Kumar Paul
自定义字段需要类型转换event-start-date 和event-end-date. 然后将其与时间进行比较();date()值。您需要添加\'type\' => \'DATE\',
在元查询参数中。因此,您的元查询如下所示:
switch ($print_type) {
case \'current\':
$meta_quer_args = array(
\'relation\' => \'AND\',
array(
\'key\' => \'event-start-date\',
\'value\' => $current,
\'type\' => \'DATE\',
\'compare\' => \'<=\',
),
array(
\'key\' => \'event-end-date\',
\'value\' => $current,
\'type\' => \'DATE\',
\'compare\' => \'>=\'
)
);
break;
case \'upcoming\':
$meta_quer_args = array(
\'relation\' => \'AND\',
array(
\'key\' => \'event-start-date\',
\'value\' => date(),
\'compare\' => \'>=\',
\'type\' => \'DATE\',
)
);
break;
case \'past\':
$meta_quer_args = array(
\'relation\' => \'AND\',
array(
\'key\' => \'event-start-date\',
\'value\' => date(),
\'type\' => \'DATE\',
\'compare\' => \'<\',
)
);
break;
default:
$meta_quer_args = array(
\'relation\' => \'AND\',
array(
\'key\' => \'event-end-date\',
\'value\' => date(),
\'type\' => \'DATE\',
\'compare\' => \'>=\',
)
);
break;
}