List custom post type by custom field date

那年仲夏 提交于 2020-01-13 05:47:07

问题


I'm working with Wordpress and WP-Types plugin and need to sort CPT by a custom field date.

This work fine:

$args = array(
    'post_type' => 'parties',
    'paged' => $paged,
    'meta_key' => 'wpcf-parties_date',
    'orderby' => 'meta_value',
    'order' => 'DESC',
);

The orderby works perfect. On the Database the value of the field date 'wpcf-parties_date' is store in this way ex: 1349481600 .

I have two templates where i need to show past and upcoming Posts. My question is how can i display only the future or past posts regarding the current date?

I try this with no luck.

$args = array(
    'post_type' => 'parties',
    'paged' => $paged,
    'meta_key' => 'wpcf-parties_date',
    'meta_value' => date('d.m.Y H:i:s'),
    'meta_compare' => '>',
    'orderby' => 'meta_value',
    'order' => 'ASC'
);

I using WP_Query for the loop.

Thanks in advance!!


回答1:


You may try meta_query to check both < and > and also use meta_value_num because your custom field value is numeric (1349481600).

$current_date=strtotime(date('d.m.Y H:i:s'));
$args = array(
    'post_type' => 'parties',
    'paged' => $paged,
    'meta_key' => 'wpcf-parties_date',
    'orderby' => 'meta_value_num',
    'order' => 'ASC',
    'meta_query' => array(
        array(
            'key' => 'wpcf-parties_date',
            'value' => $current_date,
            'compare' => '>'
        ),
        array(
            'key' => 'wpcf-parties_date',
            'value' => $current_date,
            'compare' => '<'
        )
    )
);

Read the documentation for more.



来源:https://stackoverflow.com/questions/13610836/list-custom-post-type-by-custom-field-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!