通过数据表查询日期范围内的文章

假设自定义文章类型是$type=‘books’;

global $wpdb;
$dates = $wpdb->get_results("SELECT DISTINCT DATE_FORMAT(post_date,'%Y.%m') AS `time` FROM $wpdb->posts WHERE post_type = '$type' AND  post_status = 'publish' ORDER BY post_date DESC", ARRAY_A);
var_dump($dates);

会得到如下数组:


    array(1) {
  [0]=>
  array(1) {
    ["time"]=>
    string(7) "2024.01"
  }
}

explode()将字符串转化为数组。

foreach ($dates as $date) {$time = $date['time'];
        $time_array = explode(".", $time);
var_dump($time_array);
}
array(2) {
  [0]=>
  string(4) "2024"
  [1]=>
  string(2) "01"
}

然后按照年份和月份查询文章。