Frontend filter posts by years (display yearly archives), by published date

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 or date.
    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 or date
    $GLOBALS[ 'cvp_theme_lfdpt' ] = 'post'; // Can change to another post type
    $GLOBALS[ 'cvp_theme_lfdvar' ] = 'cvp_published_year';
    $GLOBALS[ 'cvp_theme_lfdtype' ] = 'year'; /** Or change to 'published_date' if you want to filter by published date */
    add_action( 'admin_head', 'cvp_theme_add_ctf_dmy_to_exising_posts' );
    function cvp_theme_add_ctf_dmy_to_exising_posts() {
    	$option = 'cvp_theme_add_ctf_year' . $GLOBALS[ 'cvp_theme_lfdpt' ];
    	if ( !get_option( $option ) ) {
    		global $wpdb;
    		$mval = ($GLOBALS[ 'cvp_theme_lfdtype' ] === 'published_date') ? "DATE_FORMAT(post_date_gmt, '%Y-%m-%d')" : 'YEAR(post_date_gmt)';
    		$wpdb->query( "INSERT INTO {$wpdb->postmeta} (post_id,meta_key,meta_value)
      SELECT ID, '{$GLOBALS[ 'cvp_theme_lfdvar' ]}', {$mval}
      FROM {$wpdb->posts} WHERE {$wpdb->posts}.post_type = '{$GLOBALS[ 'cvp_theme_lfdpt' ]}' AND {$wpdb->posts}.post_status = 'publish'" );
    		add_option( $option, 1, '', false );
    add_action( 'save_post', 'cvp_theme_add_ctf_dmy_to_new_posts' );
    function cvp_theme_add_ctf_dmy_to_new_posts( $post_id ) {
    	if ( !wp_is_post_revision( $post_id ) && get_post_type( $post_id ) === $GLOBALS[ 'cvp_theme_lfdpt' ] ) {
    		$val = ($GLOBALS[ 'cvp_theme_lfdtype' ] === 'published_date') ? 'Y-m-d' : 'Y';
    		update_post_meta( $post_id, $GLOBALS[ 'cvp_theme_lfdvar' ], get_the_date( $val, $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

    If you want to show frontend filter by published date, please select the option Date for “Value Type”.

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

Best regards,

Scroll to Top