Quantcast
Channel: wordpress – Gary Sieling
Viewing all articles
Browse latest Browse all 9

WordPress: Add custom text to posts matching a tag

$
0
0

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;
  }

Viewing all articles
Browse latest Browse all 9

Trending Articles