Shortcode with ‘year’ parameter

The question:

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;
}

**

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

With help from @bosco , I was able to figure it out. Below is the working code:

//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;
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment