使用get_posts方法获取上周的帖子

时间:2014-09-05 13:35:04

标签: wordpress

我如何在这里提供日期参数,以便我收到上周的帖子。

请注意,这只是设置为仅在星期一运行的插件的一部分。所以我想从上周一到昨天(周日晚上11:59)收到帖子。

我知道有使用WP_Query的方法但由于我不习惯使用WP_Query并获得意想不到的结果我想坚持使用这个get_posts方法

$posts_in_category = get_posts(array('category' => $category_id, 'post_status' => 'publish'));

3 个答案:

答案 0 :(得分:1)

对于您要执行的操作,我建议您使用WP_Query而不是get_posts()get_posts()在可以提取的帖子范围方面非常有限,因为您只能指定少量搜索条件。 WP_Query(这是get_posts()使用的)允许您指定大量额外条件,包括日期参数。

请参阅: http://codex.wordpress.org/Class_Reference/WP_Query#Date_Parameters

以下是WordPress codex中的一个修改示例,它提取上周发布的帖子:

//WP_Query Arguments
$args = array(
    'date_query' => array(
        array(
            'column' => 'post_date',
            'after' => '1 week ago',
        )
    ),
    'posts_per_page' => -1
);

//Execute WP_Query (Results placed in $the_query)
$the_query = new WP_Query($args);

//The WordPress Loop
if ($the_query->have_posts()) { //Check if there are any posts returned in $the_query
    echo '<ul>';
    while ($the_query->have_posts()) { //Loop through posts returned in $the_query
        $the_query->the_post();
        echo '<li>' . get_the_title() . '</li>';
    }
    echo '</ul>';
} else { //If no posts found
    echo "No Posts Found";
}

//Reset WordPress Post Data
wp_reset_postdata();

WordPress codex中的此流程图演示了WP_Queryget_posts()的工作原理:

enter image description here

相关法典条目:

WP_Query:http://codex.wordpress.org/Class_Reference/WP_Query

答案 1 :(得分:1)

你可以在没有循环的情况下实现这一点,使用WP中的许多黑客之一。 首先创建一个名为filter_where()的函数,该函数包含SQL“WHERE”条件。然后,在开始循环之前,filter_where()函数被挂钩到WordPress的post_where()函数中。

结果,filter_where()函数中包含的“WHERE”子句被添加到post_where()函数中包含的SQL查询的末尾,这意味着循环将返回仅在两个日期之间发布的帖子在filter_where()函数中指定。

并使用今天的日期和上周的日期,自动生成 EXAMLPE:

<?php

$date_current = date("Y-m-d");// current date
$date_old = strtotime(date("Y-m-d", strtotime($date)) . " -1 week");

  function filter_where($where = '') {
        $where .= " AND post_date >= $date_old  AND post_date <= $date_current ";
    return $where;
  }
add_filter('posts_where', 'filter_where');
query_posts($query_string);
while (have_posts()) :
      the_post();
      the_content();
endwhile;

?>

答案 2 :(得分:0)

您也可以使用这种更安全或第一种方式,但由于存在安全风险,只需使用prepare语句。

<?php
$current_day = date('j');
$last_year = date('Y')-1;
query_posts('day='.$current_day.'&year='.$last_year);
if (have_posts()):
    while (have_posts()) : the_post();
       the_title();
       the_excerpt();
    endwhile;
endif;
?>

请参阅:codex.wordpress.org/Class_Reference/WP_Query#Date_Parameters

获取要显示结果的日期的参数