WordPress如何按日期选择器搜索帖子?

时间:2018-10-08 11:22:18

标签: wordpress date search filter

我正在WordPress网站上工作,我有自己的搜索过滤器页面,在其中添加了jquery datepicker,现在我想按datepicker搜索帖子?

HTML代码

script>
$(function() {

   jQuery( "#datepicker-13" ).datepicker({
       dateFormat : "yy-mm-dd"
   });
   $("#datepicker-13").datepicker().datepicker("setDate", new Date());
});
</script>

<input type = "text" name="datefrom" class="form-control alertform" id = "datepicker-13">

Wordpress查询

$datefrom = $_POST['datefrom'];

if(!empty($datefrom) && $datefrom !=='')
{
   $args    = array(
   'post_type' => 'post',
   'posts_per_page' =>8,
   'paged' => $paged,
   'post_date'  => $datefrom,
   'post_status' => 'publish' 
    );
}
 $my_query = new WP_Query($args);

这是解决方案

$datefrom = $_POST['datefrom'];
$time  = strtotime($datefrom);
$day   = date('d',$time);
$month = date('m',$time);
$year  = date('Y',$time);

$args = array(

    'post_type' => 'post',
    'posts_per_page' =>8,
    'paged' => $paged,

'date_query' => array(
    array(
   'year'  => $year,
   'month' => $month,
   'day'   => $day,
),
),
);

1 个答案:

答案 0 :(得分:0)

在查询之前,您需要按以下方式将日期分为“年”,“月”和“日期”。

$datefrom = $_REQUEST['datefrom'];
$datefromsplit = explode("-", $datefrom);
$yearval = $datefromsplit[0];
$monthval = $datefromsplit[1];
$dateval = $datefromsplit[2];

if(!empty($datefrom) && $datefrom!='')
{
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => 8,
        'paged' => $paged,                      
        'year'  => $yearval,
        'monthnum' => $monthval,
        'day' => $dateval
    );
}
$my_query = new WP_Query($args);

您可以在WordPress Codex上阅读更多内容。