Categorising posts/pages into years published

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..