Wordpress:查询年份范围内的年份

时间:2016-01-19 22:51:41

标签: wordpress

我有一个start_year和一个end_year

f.e:Project-Lorem-Ipsum:$ start_year = 2001,$ end_year = 2005

我需要选择某一年(f.e. $ filter_year = 2002)并显示今年正在运行的帖子。 这意味着,$ filter_year可以是$ start_year或$ end_year,也可以是$ start_year和$ end_year。

我做了这个草图,以便更好地展示我需要的东西, 谢谢你的帮助!

$filter_year=2002;    

$posts = get_posts(array(
'posts_per_page' => -1, 
'post_type'     => 'post',
'meta_query'    => array(
    'relation'      => 'AND',
    array(
        'key'       => 'start_year',
        'value'     => $filter_year,
        'compare'   => '???',
    ),
    array(
        'key'       => 'end_year',
        'value'     => $filter_year,
        'compare'   => '???',
    ),
),

1 个答案:

答案 0 :(得分:0)

您可以使用元查询。但是,如果尚未实施这些工作,还需要做出改变。

1:您可以在元查询中使用日期类型,但它只能以yyyy-mm-dd格式使用

$start_date = date('Y-m-d',  strtotime('1/1/15') ); // cant just use the year, it will see it as a time value
$end_date = date('Y-m-d',  strtotime('31/12/15') ); // cant just use the year, it will see it as a time value

'meta_query' => array(
    'relation' => 'AND'
    array(
        'key' => 'start_year',
        'value' => $start_date,
        'compare' => '>='
    ),
    array(
        'key' => 'start_year',
        'value' => $end_date,
        'compare' => '<='
    ),
)

2:将日期转换为时间戳(首选)

$start_date = strtotime('1/1/15'); // cant just use the year, it will see it as a time value
$end_date = strtotime('31/12/15'); // cant just use the year, it will see it as a time value

'meta_query' => array(
    'relation' => 'AND'
    array(
        'key' => 'start_year',
        'value' => $start_date,
        'compare' => '>='
    ),
    array(
        'key' => 'start_year',
        'value' => $end_date,
        'compare' => '<='
    ),
)

您可以使用wp_query或get_posts循环遍历元值,并检查get_post_meta($postid, 'start_year', true);是否存在。