admin管理员组文章数量:1204355
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()
本文标签: functionsAdd custom text automatically on each post
版权声明:本文标题:functions - Add custom text automatically on each post 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738682960a2106663.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论