php - WP Query post by year in 手风琴
解决方案
尝试使用自定义选择查询并使用 post_type 的推荐循环遍历每个帖子。
然后遍历结果并将WP_Query() class
date_query
参数设置为自定义选择查询结果获得的年份数组。
global $wpdb;
$posts = $wpdb->posts;
//Get all unique years as "years" from posts where post type is equal to testimonials
$sql = "SELECT DISTINCT(YEAR(`post_date`)) as years FROM $posts WHERE post_type = 'testimonials' ORDER BY years DESC"; //Get all post year list by DESC
//Loop through all results and use date_query param https://codex.wordpress.org/Class_Reference/WP_Query#Date_Parameters
$result = $wpdb->get_results($sql);
foreach($result as $rs) {
echo '<h2>'.$rs->years.'</h2>';
$args = array(
'post_type' => 'testimonials',
'post_per_page'=> -1,
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'DESC',
'date_query' => array(array(
'year'=> $rs->years,
),),
);
$loop = new WP_Query($args);
if($loop->have_posts()) {
while($loop->have_posts()) : $loop->the_post();
echo '<a href="'.get_permalink().'">'.get_the_date().'</a>';
endwhile;
}
}