Custom title widget / HTML encoding

I’m not the first person who has battled the matter of WordPress stripping HTML from widget titles. There are a number of custom widgets out there that allow you to add e.g. links to titles, but I specifically wanted the ability to add br and span tags.

I came across this tutorial: http://ponderwell.net/2011/05/how-to-use-html-in-wordpresss-widgets-title/ which tells you how to create a custom widget file based on the native WP default-widgets.php.

Read More

That gets me nearly there, but both with using his method directly, or adapting it to customize an existing widget (Enhanced Text Widget), I’m getting an output of <br> and <span> instead of proper HTML encoding. I saw that somebody in the comments mentions html_entity_decode() and have tried a few things, but honestly I don’t know PHP well enough to get it to work.

If I have to do this in functions.php plus a custom_widgets.php file, I’ll make that work, but for portability’s sake, I’d prefer to accomplish the task as a widget plugin.

What do I need, specifically, to get those tags properly encoded now that I’ve come this far? I did find the solution offered by Chris here: Unfiltered html in widget title not working, but clearly am not putting that code in the correct place. (I did get Amy’s own self-solution to work in the functions.php, but not sure if that’s a great way of doing it….)

TIA.

Related posts

1 comment

  1. As you know, html tags doesn’t work on widget title. But there’s work around to use it. The best approach i know is to use shortcode in title. So, for using br and span, the following is a solution –

    add_filter('widget_title', 'do_shortcode');
    
    add_shortcode('br', 'wpse_shortcode_br');
    function wpse_shortcode_br( $attr ){ return '<br />'; }
    
    add_shortcode('span', 'wpse_shortcode_span');
    function wpse_shortcode_span( $attr, $content ){ return '<span>'. $content . '</span>'; }
    
    add_shortcode('anchor', 'wpse_shortcode_anchor');
    function wpse_shortcode_anchor( $attr, $content ){ 
        return '<a href="'. ( isset($attr['url']) ? $attr['url'] : '' ) .'">'. $content . '</a>'; 
    }
    

    You can simply put these lines to your functions.php file.

    Usage:

    As like shortcode usage on post content, use it on the widget title.
    [br]
    [span]something[/span]
    [anchor url="http://domain.com/"]something[/anchor]

    One issue

    Most of the widgets use a filter on widget title widget_title, but some custom widget might not apply or use this hook. So, on those widgets, this method will not work, and i guess other method wouldn’t.

Comments are closed.