2014-09-05 45 views
0

我如何提供日期参数在这里,以便我从上周获得帖子。使用get_posts方法获取上周的帖子

请注意,这是插件的一部分,只能在星期一运行。所以我想从上周一到昨天(周日下午11:59)获得帖子。

我知道有方法通过使用WP_Query但因为我不是在使用WP_Query并获得意想不到的效果舒服,我想用这种get_posts方法

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

回答

1

坚持为你正在尝试做的,我d推荐使用WP_Query而不是get_posts()get_posts()在它可以提取的帖子范围内的范围非常有限,因为您只能指定少量的搜索条件。 WP_Query(这是get_posts()使用的)允许您指定大量额外条件,包括日期参数。

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

这里是WordPress的抄本,其获取在上周的帖子变形例:

//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抄本该流程图演示了如何WP_Queryget_posts()工作:

enter image description here

相关法典条目:

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

+0

我尝试使用WP_Query,但它不是取结果 – 2014-09-05 14:07:23

+0

针对日期参数你说你已经尝试过WP_Query,或者我的代码不工作? – Mastrianni 2014-09-05 14:11:00

+0

@mastianni不,我说我已经尝试WP_Query,但是看到你的代码后,我发现我的错误:)感谢很多 – 2014-09-05 14:23:18

1

可以achievethis不循环,使用许多黑客之一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; 

?> 
+0

为什么人们不鼓励query_posts呢?它会返回与get_posts相同的posts数组吗? – 2014-09-05 14:26:14

+1

'query_posts'不是由WordPress codex推荐的,还有更好的内置方法来获取帖子。你可以阅读为什么不建议在本页的第一段:http://codex.wordpress.org/Template_Tags/query_posts – Mastrianni 2014-09-05 14:32:22

+1

WordPress循环功能非常强大,以及query_posts()函数,它允许您指定一些循环检索帖子的参数。虽然,没有内置函数或参数可以在两个日期之间获取帖子。 – user3042036 2014-09-05 14:41:48

0

您也可以使用这种方式,这是更安全还是第一位的,但只使用准备语句,因为安全风险。

<?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

得到你想要显示的结果