Like often in WordPress, the simpliest way to alter the core is to…dive in it and look for hooks!
In the file wp-includes/default-widgets.php there is a filter hook called ‘widget_title’. That’s the one we need.
It requires 3 parameters to work : the title we want to return, the instance (contextual data of the widget) and the id of the current widget.
Below is the list of id’s of default widgets in WordPress :
- pages
- calendar
- archives
- links
- meta
- search
- text
- categories
- recent_posts
- recent_comments
- rss
- tag_cloud
- wp_nav_menu_widget
In the following example, we change the title of the widget if we are in the following context :
- the widget is recent_posts widget mandatory contextual information, otherwise all widgets will have the same title.
- Contextual parameter 1 : we display a single post (not archive, or search for example)
- Contextual parameter 2 : we display a particular post type
You can play with those contextual parameters and even use a switch() for each widget type. In this example it is pretty simple.
function my_widget_title($title, $instance, $id_base) { if ( is_singular() && 'my_post_type' == get_post_type() && 'recent-posts' == $id_base) { return __('Recent entries from my_post_type'); } else { return $title; } } add_filter ( 'widget_title' , 'my_widget_title', 10, 3); //we use the default priority and 3 arguments in the callback function
That’s it!
6 thoughts on “Dynamically changing the widget title depending on the context”
Hi aaronkine,
The developer team handles support for Customizr at https://wordpress.org/support/theme/customizr and for Customizr-Pro at http://presscustomizr.com/support/. Please post your query there with a link to your site.
I can get this to work for only SOME of my widget titles? Why would some work and some not?
It works for this plugin Recent Posts Plus, using ID_Base “recent-posts-plus”. and also works with widget Recent Jobs (which is WP Job Manager plugin) using $id_base “widget_recent_jobs”. But I cannot get this to work wtih my other ones. The Events Calendar Plugin with $id_base “tribe-events-adv-list-widget”. and other plugin Another Wordpress Classifieds Plugin with $id_base “awpcp-latest-ads”. Any idea why this will work for some but not others??
Hi,
The formatting and an image inserted to the right in the 3 widgets area above footer are not showing correctly – but am only having this error in the sub-pages e.g. /team or /products
They show correctly on all other main menu pages as you can see
I use a child theme with Customizr Pro – simplesolutionsinclusive.com
any solution to this?
Tried posting this on the forum – no replies
Thank you!
Hi Nic , how to change my_post_type into the name of parent category ?
so the widget title will be the parent category name.
thanks
Hi Aris,
you’ll probalby want to access the current category with get_queried_object()
I hope this will help 🙂
I want to change the color of the Widget titles, how do I go about it please.
Thanks