I would like to display posts with a 'year' parameter. For example: to display posts from 2020, the shortcode should look like [archived-posts year="2020"]. I have tried my code below but it's not working. Maybe the 'meta_value' is not correct? Any help would be appreciate it.
Thanks!
//get archived posts
add_shortcode( 'archived-posts', 'archived_posts' );
function archived_posts() {
$atts = shortcode_atts( array( 'year' => date('Y') ), $atts );
$buffer = '<h3>Post Titles</h3>';
$q = new WP_Query(array(
'post_type' => 'post',
'posts_per_page' => -1 ,
'meta_key' => 'post_date',
'meta_value' => $atts['year'],
'post_status' => 'archive' ,
//'year' => 2021,
));
while ($q->have_posts()) {
$q->the_post();
$buffer = $buffer.get_the_title().'<br>';
}
wp_reset_postdata();
return $buffer;
}
**EDIT June 20th 2021
I was able to make the code work the the year parameter, but now it only shows one result for each year. So maybe the loop is broken or something?! Please see updated code below.
//get archived posts per year
add_shortcode( 'archived-posts', 'archived_posts' );
function archived_posts($atts) {
$a = shortcode_atts( array( 'year' => date('Y') ), $atts );
$q = new WP_Query(array(
'post_type' => 'post',
'posts_per_page' => -1 ,
'post_status' => 'archive' ,
'year' => $a['year'],
));
while ($q->have_posts()) {
$q->the_post();
$buffer = '<div class="archived-post-item"><a href="'.get_permalink().'">'.get_the_title().'</a></div>';
}
wp_reset_postdata();
return $buffer;
}
**
WP_Query
documentation page - specifically, the bit on Date Parameters. You'll also need to actually define the$atts
variable as a function argument, as detailed in the Shortcode section of the Plugin Handbook