最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

functions - Add custom text automatically on each post

programmeradmin2浏览0评论

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 badges
Add a comment  | 

1 Answer 1

Reset to default 1

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

  • the_content filter
  • preg_replace()
发布评论

评论列表(0)

  1. 暂无评论