Add “This Year” to WordPress Automatically: Post Titles, Content, Everywhere

This post goes well together with the video:

I like to use two versions of this shortcode.

First is the honest one – it will flip the year only if the post was actually updated this year. It’s a helper so that you don’t have to remember about setting that date by hand – especially if you mention it in multiple places.

add_shortcode( 'this_year', function () {
  //get last modified date of current post/page
  $out = get_the_modified_date('Y');
  
  //if featching date failed, default to current year
  if(!$out) $out = date("Y");

  //return year
  return $out;
} );

The other version is your “I don’t care, just show the current year!” version:

add_shortcode( 'this_year', function () {
  $offset = "-10 days"; //Comment out to disable the offset; this is so that the code doesn't roll on Jan 1

  $out = isset($offset) ? date("Y", strtotime($offset)) : date("Y");

  //return year
  return $out;
} );

Optional code to add if you want to be able to use shortcodes in post titles:

add_filter( 'the_title', 'do_shortcode' );

You can add those shortcodes through a snippet plugin like Code Snippets for example.