worpdress搜索指定时间内的文章

有朋友问,wordpress的搜索结果能否出现近十天的内容?虽然我不知道他这奇怪的需求是要干啥,但是是可以的。

一般要改变前台的结构,我都用pre_get_posts钩子,然后判断是否是搜索页面,加上日期搜索的条件即可。

代码如下:

  1. function ashuwp_custom_posts_per_page($query){
  2.   //非后台、搜索页面、主循环
  3.   if(!is_admin() && is_search()&& $query->is_main_query()){
  4.     $today = getdate(); //获取当前时间
  5.     $ago_time = strtotime("-10 days"); //十天前的时间戳
  6.     $days_ago = getdate($ago_time); //按时间戳返回十天前的日期
  7.     $date_args = array(
  8.       array(
  9.         'after' => array(
  10.           'year' => $days_ago['year'],
  11.           'month' => $days_ago['mon'],
  12.           'day' => $days_ago['mday'],
  13.         ),
  14.         'before' => array(
  15.           'year' => $today['year'],
  16.           'month' => $today['mon'],
  17.           'day' => $today['mday'],
  18.         ),
  19.         'inclusive' => true, //启用after  before
  20.       ),
  21.     );
  22.     $query->set('date_query', $date_args);
  23.   }
  24.   return $query;
  25. }
  26. add_action('pre_get_posts','ashuwp_custom_posts_per_page');

将上述代码复制到主题的functions.php文件中即可,当然如果有更奇怪的需求,可以对照上面的的注释修改。

end.

本篇教程之前的几篇教程是

本篇教程之后的几篇教程是

没有找到你要找的内容?你可以通过搜索你要找的内容,或者给我们留言。

已有0评论

暂时木有评论.

发表评论