Add custom text automatically on each post

You can use a regular expression to sniff for it on the the_content filter.

add_filter( 'the_content', 'wpse403518_custom_text' );
function wpse403518_custom_text( $content ) {
    $regex   = '/^([^\.!?]+)([\.!?])(.*)$/';
    $replace="$1 2022$2$3";
    $content = preg_replace( $regex, $replace, $content );
    return $content;
}

The regex

The $regex variable is a regular expression, and what it does, roughly, is this:

  • ^ means the start of the string; then
  • ([^\.!?]+) means “match everything that is not a ., !, or ? one or more times” (ie, the first sentence, until we hit a ., !, or ?); then
  • ([\.!?]) means “match a single ., !, or ?” (ie, the first sentence-ending punctuation in the string); then
  • (.*) means “all the characters”; then
  • $ means “the end of the string”.

The $replace variable assigns $1 to the first group above (the first sentence), $2 to the second group (ie, the first ., !, or ?), and $3 to the third group (ie, the rest of the content). So what happens is that the 2022 gets inserted between the first sentence and the punctuation at its end, then the rest of the text gets printed as normal.

References