Add HTML Tags in Post and Widget Titles

In a recent project, I needed to use <span /> tags to add some styles (just color, actually) to post and widget titles. By default β€” and there’s no hook to disable this β€” WordPress strips any HTML tags found in post and widget titles. Here’s my solution to this problem. Please keep in mind that I only needed to add <span /> tags, so if you need to add more tags, you should modify the code to fit your needs πŸ™‚

First, add the span tags to the desired post and widget titles, replacing the < and > characters with hashes ( # ):

Add fake span tags to post and widget titles

Now, let’s create a tiny mu-plugin to handle our HTML tags. We’ll be using four filter hooks for this:

  • the_title, triggered in post titles
  • the_title_rss, triggered in post titles for feeds
  • wp_title, triggered in HTML document title, and
  • widget_title, triggered in β€” well, you guessed it right β€” widget titles

The plugin:

/*
Plugin Name: Enable HTML tags in post and widget titles
Author: Dzikri Aziz
Author URI: /
Version: 0.1
License: GPL v2
*/


function kc_convert_title_html_tags( $string ) {
  global $wp_current_filter;
  $filter = end($wp_current_filter);
  $search = array('#span#', '#/span#');
  $replace = ( in_array($filter, array('wp_title', 'the_title_rss')) || ($filter == 'the_title' && (is_admin() || in_array('wp_head', $wp_current_filter))) ) ? '' : array('<span>', '</span>');
  $string = str_replace( $search, $replace, $string );

  return $string;
}

add_filter( 'the_title', 'kc_convert_title_html_tags' );
add_filter( 'the_title_rss', 'kc_convert_title_html_tags' );
add_filter( 'wp_title', 'kc_convert_title_html_tags' );
add_filter( 'widget_title', 'kc_convert_title_html_tags' );

Take a closer look to the replacement string. We need to strip our fake HTML tags from the post titles when:

  • kc_convert_title_html_tags() is called by wp_title or the_title_rss hook
  • the_title filter hook is triggered from within wp_head action hook (eg. the post title is used by the title attribute of feed links
  • we’re viewing a post table in admin area.

However, when we’re inside the <body />, they need to be converted to the real tags.

That’s it! πŸ™‚

Standard