问题
I'm trying to get the testimonials (custom post type) in following order.
I can easily retrieve posts using WP_Query class but struggling to create an accordion as shown in the screenshot above.
回答1:
Try using a custom select query and looping through each post with a post_type of testimonial.
Then loop through result and set WP_Query() class
date_query
param to an array of the years obtained by the custom select query result.
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;
}
}
回答2:
@user3325126 Great code, thanks :) Just replace 'post_per_page'=> -1, into 'posts_per_page'=> -1, (missing one s) It should be
'posts_per_page'=> -1,
来源:https://stackoverflow.com/questions/52492728/wp-query-post-by-year-in-accordion