“is_new_day()” alternative for years?

I don’t believe there’s a is_new_year() function in WordPress, as an alternative for is_new_day(). I’m trying to display the year only once for each set of posts, what would be the best way to do this?

Should I just check the date manually with PHP in the loop or are there any better ways?

Related posts

Leave a Reply

1 comment

  1. You could create a helper function that returns a year number only once per year:

    function get_unique_year( $post_id = 0 )
    {
        static $last = 0;
    
        $post_id || $post_id = get_the_ID();
    
        $year = get_the_time( 'Y', $post_id );
    
        if ( $year === $last )
            return;
    
        $last = $year;
    
        return $last;
    }
    

    Then fetch your posts and use that helper:

    $posts = wp_get_recent_posts(); // or any other function returning posts
    
    foreach ( $posts as $post )
        if ( $year = get_unique_year( $post->ID ) )
            print "Year: $year<br>";