查询在Wordpress中的特定日期之后发布的帖子

Spa*_*awk 5 wordpress

我正在尝试写一个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");
Run Code Online (Sandbox Code Playgroud)

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

小智 11

从WordPress版本3.7开始,WP_Query参数date_query对于这种类型的查询非常有效.

正如您在Codex中看到的,您可以使用after参数指定日期查询.该after可以是一个的strtotime() -兼容的字符串,或"年","月","日"值的数组.

对于您的示例,以下内容应该起作用:

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

或者使用strtotime() - 字符串:

$args = array(
    'posts_per_page' => -1,
    'date_query'     => array( 'after' => '2012-03-01' ),
);
$custom_query = new WP_Query( $args );
Run Code Online (Sandbox Code Playgroud)


lti*_*_sh 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' );
Run Code Online (Sandbox Code Playgroud)