1

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?

1 Answer 1

2

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>";
3
  • I don't understand why you're comparing with $last this variable is always 0, isn't it? Commented Apr 28, 2013 at 11:20
  • @user2019515 no, it will be updated each time the year changes.
    – fuxia
    Commented Apr 28, 2013 at 13:42
  • Oh right, I see now, thanks! Can I put this code in my functions.php file so I can use the function everywhere? I assume I need to make a filter for that then? What would you advice if I need it in multiple files? Commented Apr 28, 2013 at 18:31

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.