Dynamically changing the widget title depending on the context

⚠️ Code snippets might not be compatible with the latest version of your theme. Always use a child theme to customize your theme, and test your code on a staging website before migrating to production.

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”

Comments are closed.