WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a case where that are a lot of widgets in several custom sidebars. I am wondering if there is a simple way to alter the titles of each widget dynamically. Typically a widget has a title field you can set manually or on the plugin itself.

I wish to add something like a meta field value per post to each widget title.

The logic would be something like:

$dynamic_title = get_the_title();
// add a filter to change the widget titles per post value
// The widget title would be something like "Recent Posts for $dynamic_title"

I know there is a widget_title filter but how do you target specific widgets?

ps. I cannot use the regular register_sidebar parameters due to having many widgets needing specific titles.

share|improve this question
up vote 7 down vote accepted

You can use the widget_display_callback (fired, predictably, just prior to displaying a widget :) ).


function wptuts54095_widget_custom_title($instance, $widget, $args){

    if ( is_single() ){
       //On a single post.
       $title = get_the_title();
       $instance['title'] = $instance['title'].' '.$title;

    return $instance;

The $widget argument is an object of your widget class, and so $widget->id_base will contain the ID for your widget (if targeting a specific widget class).

share|improve this answer

You can use your own hook for widget_title action. You can determine specific widget by $id_base parameter which is passed as third argument to the hook. It should work like this:

function myplugin_widget_title( $title, $instance, $id_base ) {
    if ( !is_single() ) {
        return $title;

    $post_title = get_the_title();
    switch ( $id_base ) {
        case 'pages': return sprintf( '%s "%s"', $title, $post_title );
        case 'links': return sprintf( 'Links for "%s" post.', $post_title );
        // other widgets ...
        default: return $title;
add_filter( 'widget_title', 'myplugin_widget_title', 10, 3 );

For custom widgets you will need to apply this filter to the widget's title before echoing it (as shown the default widgets):

$title = apply_filters('widget_title', empty( $instance['title'] ) ? __( 'Pages' ) : $instance['title'], $instance, $this->id_base);
share|improve this answer
+1 a neat answer - but it does require the widget to apply the widget_title filter. – Stephen Harris Jun 3 '12 at 19:11
Where you able to test this with the default 'links', I cannot get it to work, maybe because it is missing the widget_title? – Wyck Jun 3 '12 at 22:56

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.