List posts by year (display yearly archives)

If you want to show list of years, and list of posts in each year, this document will help.
We will leverage the live filter for the custom field to display yearly archives, with only 2 steps:

  • Step 1: add a custom field to every existing and upcoming posts, to store the published year.
    Please add this code to file functions.php in the theme’s folder (or install this plugin Code Snippets then add this code to the “Code” textarea):

    // Content Views Pro - add custom field to store the published year
    add_action( 'admin_head', 'cvp_theme_add_ctf_to_exising_posts' );
    function cvp_theme_add_ctf_to_exising_posts() {
    	if ( !get_option( 'cvp_theme_add_ctf_to_posts' ) ) {
    		global $wpdb;
    		$wpdb->query( "INSERT INTO {$wpdb->postmeta} (post_id,meta_key,meta_value)
      SELECT ID, 'cvp_published_year', STR_TO_DATE(post_date_gmt,'%Y')
      FROM {$wpdb->posts} WHERE {$wpdb->posts}.post_type = 'post' AND {$wpdb->posts}.post_status = 'publish'" );
    		add_option( 'cvp_theme_add_ctf_to_posts', 1, '', false );
    	}
    }
    add_action( 'save_post', 'cvp_theme_add_ctf_to_new_posts' );
    function cvp_theme_add_ctf_to_new_posts( $post_id ) {
    	if ( wp_is_post_revision( $post_id ) )
    		return;
    	update_post_meta( $post_id, 'cvp_published_year', get_the_date( 'Y', $post_id ) );
    }
    // End code
    
  • Step 2: Create a new View to show the years list, and allow visitors to filter posts by year.
    In Admin area, click Content Views > Add New menu item. In Filter Settings tab of the View, select Custom Fields in Advance group, then click Add New button. A new field will be added, please select options as same as here:

    Content Views Pro - live filter by year

Then you can save the View, and add View shortcode to where you want to display the yearly archives.

Best regards,