5

我正在尝试写一个WP_Query我只调用 2012 年 3 月之后发布的帖子的地方。我可以成功地调用 2012 年 3 月发布的帖子,但“从 2012 年 3 月起”很难做到。

    $current_year = date('2012');
    $current_month = date('>3'); // This doesn't work
    $current_month = date('3'); // This DOES work

    $custom_query = new WP_Query("year=$current_year&monthnum=$current_month&order=ASC&posts_per_page=-1");

我错过了一些简单的东西,还是必须变得更复杂?

4

2 回答 2

15

从 WordPress 3.7 版开始,WP_Query 参数date_query非常适合这种类型的查询。

正如您在 Codex 中看到的,您可以使用参数指定日期查询afterafter可以是与 strtotime() 兼容的字符串,也可以是“年”、“月”、“日”值的数组。

对于您的示例,类似以下内容应该有效:

$args = array(
    'posts_per_page' => -1,
    'date_query'     => array(
        'after' => array(
            'year'  => 2012,
            'month' => 3,
            'day'   => 1,
        ),
    ),
);
$custom_query = new WP_Query( $args );

或者使用 strtotime()-string:

$args = array(
    'posts_per_page' => -1,
    'date_query'     => array( 'after' => '2012-03-01' ),
);
$custom_query = new WP_Query( $args );
于 2015-07-06T13:50:16.830 回答
8

http://codex.wordpress.org/Class_Reference/WP_Query中的“时间参数”部分有关于日期范围的注释。使用相同的技术:

$query_string = "order=ASC&posts_per_page=-1";

// Create a new filtering function that will add our where clause to the query
function filter_where( $where = '' ) {
    $where .= " AND post_date >= '2012-03-01'";
    return $where;
}

add_filter( 'posts_where', 'filter_where' );
$custom_query = new WP_Query( $query_string );
remove_filter( 'posts_where', 'filter_where' );
于 2012-05-28T00:25:18.957 回答