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.

2 s
2

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

add_filter('widget_display_callback','wptuts54095_widget_custom_title',10,3);

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).

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *