Customize WordPress footers by tag

Using the WordPress APIs, you can add custom footers to posts that key off tags. For instance, you could add links to related books on Amazon based on the topic of a post.

This example will map tags to custom footers, as well as optionally add a random footer for posts without one of the selected tags.

add_filter('the_content', 'custom_category_text');
 
function custom_category_text($content){
  global $post;
 
  if(!is_single()) {
    return $content;
  }
 
  $regexes = array(
    "tag1" => "/\b(tag1|tag_1|tag-1)\b/i",
    "tag2" => "/\b(tag2)\b/i"
  );
 
  $ads = array(
    "tag1" => '<p>Content 1</p>',
    "tag2" => '<p>Content 2</p>',
  );
 
  $posttags = get_the_tags();
  $found = '';
 
  foreach ($regexes as $type => $re) {
    if ($posttags) {
      foreach($posttags as $tag) {
        if ($found or preg_match($re, strtolower($tag->name))) {
          return $content . $ads[$type];
        }
      }
    }
 
    $slug = $post->post_name;
    if (preg_match($re, $slug)) {
      return $content . '<i>' . $ads[$type] . '</i>';
    }
  }
 
  $ads = array(
    '<p>This is a test 1</p>',
    '<p>This is a test 2</p>'
  );
 
  return $content . '<i>' . $ads[array_rand($ads, 1)] . '</i>';
}