1

I have a lot of posts/pages, and I would like to create a list in my sidebar, showing all of the years that I have created posts/pages in, so for instance, if I have 5 posts/pages that were spaced out over 5 years, from 2006 to 2011, each year having one post, I would like 2005, 2006, 2007, 2008, 2009, 2010 and 2011 to show as list items in the sidebar, as links to all of the posts/pages created that year.

Any idea of how I can achieve that?

Thanx in advance!

2 Answers 2

1

Not sure if there's a specific function for this as i didn't find anything with a quick search, but i went ahead and wrote a function to do the job, feel free to expand upon it or do whatever you like with it.

List year archives for published posts of a type

Code is provided "as is", do as you will with it.

function get_years_for_type( $type = 'post', $echo = false, $sep = '<br />' ) {
    global $wpdb, $wp_post_types;

    $type = '' == $type ? 'post' : $type;

    if( !isset( $wp_post_types[$type] ) )
        return;

    $q = $wpdb->get_col( $wpdb->prepare( "SELECT YEAR(post_date) as year FROM wp_posts WHERE post_type = %s AND post_status = 'publish' GROUP by year", $type ) );

    if( empty( $q ) )
        return;

    $y = array();
    foreach( $q as $year )
        $y[] = '<a href="' . get_year_link( $year ) . '">' . $year . '</a>';

    $y = implode( $sep, $y );

    if( $echo )
        echo $y;
    else
        return $y;
}

Example usage:

// Output list of years for pages
echo get_years_for_type( 'page' );
get_years_for_type( 'page', true ); 

// Output list of years for posts
echo get_years_for_type();
get_years_for_type( 'post', true ); 

// Storing the result in a variable
$var = get_years_for_type(); // post is assumed for type when none set

// Using an alternate seperator for the links
echo get_years_for_type( 'post', false, ' | ' );    
get_years_for_type( 'post', true, ' | ' );

Hope that helps..

0
1

There is decent native function wp_get_archives() for such, but unfortunately native archives widget doesn't use all of it and is limited to monthly archives.

Take a look at Widgets Reloaded plugin, it replaces native widgets with more configurable versions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.