WordPress: Add custom text to posts matching a tag

The example below shows how to add text to the bottom of posts, based on specific conditions.

To get the right value for “custom_text”, you likely just want to add a paragraph tag, but you can copy existing HTML from your site to get a good example.

add_filter('the_content', 'custom_category_text');
 
function custom_category_text($content){
  global $post;
  $custom_text =
    '<p>Some example text...</p>';
 
  $found = false;
  $re = "/\btag\b/i";
 
  $posttags = get_the_tags();
 
  if ($posttags) {
    foreach($posttags as $tag) {
      if ($found || preg_match($re, $tag->name)) {
        $found = true;
      }
 
      continue;
    }
  }
 
  if($found) {
    $content =  $content . $custom_text;
  }
  return $content;
}

If you want to look for specific words in the post slug, you can also add this:

  $slug = $post->post_name;
  if (preg_match($re, $slug)) {
    $found = true;
  }

One Reply to “WordPress: Add custom text to posts matching a tag”

Leave a Reply

Your email address will not be published. Required fields are marked *