Wordpress - Is there any way to dynamically alter widget titles?
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).
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);