Suppose I have a post and it's the first paragraph is:
"This a Pen. The color is red."
I want to add a custom text like "2022" after "Pen" on first sentence, at the end of the text line.
Example: "This a Pen, 2022. The color is red."
I need to add this to all of the posts automatically. Is there a way to do that? Or do I have to replace in the database?
Suppose I have a post and it's the first paragraph is:
"This a Pen. The color is red."
I want to add a custom text like "2022" after "Pen" on first sentence, at the end of the text line.
Example: "This a Pen, 2022. The color is red."
I need to add this to all of the posts automatically. Is there a way to do that? Or do I have to replace in the database?
Share Improve this question edited Mar 9, 2022 at 11:59 Angel Hess 137 bronze badges asked Mar 8, 2022 at 15:03 Mi MonirMi Monir 32 bronze badges1 Answer
Reset to default 1You 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
the_content
filterpreg_replace()