Get list of years when posts have been published

I want to create a list of posts from a Custom Post Type and add some filters the user can click to filter the list.

I added filters for all the categories by using the get_terms() function. Now I want to add filters by year, so I need a way to retrieve a list of all the years in which at least one post has been published…

I just need something like:

$years = get_all_years_with_posts();
// returns array( 2011, 2013, 2014 )

I know I can grab all the posts, check their year, and build the list myself, but is not there any other approach?

4 s
4

Your question is pretty old, but I just wanted to add a real solution to your question. Here’s a function that will return an array of years you have posts published in. You can put this function in functions.php or in a plugin or whatever you want.

function get_posts_years_array() {
    global $wpdb;
    $result = array();
    $years = $wpdb->get_results(
        $wpdb->prepare(
            "SELECT YEAR(post_date) FROM {$wpdb->posts} WHERE post_status="publish" GROUP BY YEAR(post_date) DESC"
        ),
        ARRAY_N
    );
    if ( is_array( $years ) && count( $years ) > 0 ) {
        foreach ( $years as $year ) {
            $result[] = $year[0];
        }
    }
    return $result;
}

You’ll need to modify it slightly for custom post types… just add AND wp_posts.post_type="my_cpt" somewhere in there.

Leave a Comment