简体   繁体   English

使用meta来匹配WP_Query中的日期

[英]Use meta to match date in WP_Query

I have some posts with a custom filed named "event_end_date". 我有一些帖子来自一个名为“ event_end_date”的自定义字段。 I am using Advanced custom fields for that. 我正在为此使用高级自定义字段。 How can I get the posts which have end_date older than today? 如何获得end_date比今天早的帖子? I was trying with this, but could not get through. 我正在尝试此操作,但无法通过。

$args = array(
        'cat'       => '6, -33',
        'numberposts'   => -1,
        'post_type'     => 'post',
        'meta_query'    => array(
            array(
                'key' => 'event_end_date',
                'value' => date('y-m-d'),
                'type' => 'DATE',
                'compare' => '>'
            )
        )
    );

//get results
$the_query = new WP_Query( $args );

Here I wanted those posts which have category '6' and does not have category '33'. 在这里,我希望那些类别为“ 6”而类别为“ 33”的帖子。 In the backend, the field - 'event_end_date' has these: 在后端,“ event_end_date”字段具有以下内容:

Field Type: Date Picker
Display format: 10/11/2014
Return format: 20141110

I think if you were too look more closely at the data being stored in that actual custom/meta field, you'd find that it's stored as a unix timestamp, not in the return or display format, and because of that, your problem is that your format's don't match up. 我认为,如果您过于仔细地查看存储在该实际自定义/元字段中的数据,您会发现它以unix时间戳的形式存储,而不是以返回或显示格式存储,因此,您的问题是您的格式不匹配。

You can account for that difference by using the U code for unix timestamp with date('U') instead of date('ym-d') . 您可以使用带有date('U')而不是date('ym-d') unix时间戳U代码来解决这一差异。

In that case your code would look like this: 在这种情况下,您的代码将如下所示:

$args = array(
    'cat'       => '6,-33',
    'numberposts'   => -1,
    'post_type'     => 'post',
    'meta_query'    => array(
        array(
            'key' => 'event_end_date',
            'value' => date('U'),
            'type' => 'DATE',
            'compare' => '>'
        )
    )
);

//get results
$the_query = new WP_Query( $args );

Using date('Ym-d', time()) solved the problem for me. 使用date('Ym-d',time())为我解决了这个问题。

$args = array(
        'category__and'     => array(6),
        'category__not_in'  => array(33),
        'numberposts'       => -1,
        'post_type'         => 'post',
        'post_status'       => 'publish',
        'meta_query'        => array(
            array(
                'key'       => 'event_end_date',
                'value'     => date('Y-m-d', time()),
                'type'      => 'DATE',
                'compare'   => '<'
            )
        )
    );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM