Understanding apply_filters

The question:

I get the same results with these to lines, so what does apply_filters do?

Line 1 : echo $instance['title'];

Line 2 : echo apply_filters('widget_title', $instance['title']);

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

Well, apply_filter creates a global filter hook which can be used dynamically all over the system. Which gives you the ability to filter the content of the $instance['title'], means you can over ride the content as well as can modify the content. Here is the example-

add_filter( 'widget_title', 'widget_title_to_uppercase', 10, 1);
function widget_title_to_uppercase( $content ){
    $content = strtoupper($content);
    return $content;

Now all the widget title will be uppercase. So with this filter hook you can filter the widget_title from any where the WordPress system. But with the $instance['title'] it is not possible.

Method 2

If you haven’t written a filter using add_filter obviously nothing will happen if you apply filters.

Try this in your functions.php as an example:

add_filter( 'widget_title', 'wpse236433_invert_string' );

function wpse236433_invert_string ($title) {
  return strrev($title);

Method 3

apply_filters() allows you to modify a value using a hook. Let me explain-

Sample-1: Consider this code, it’ll show Hello World!,

$str = 'Hello World!';
echo $str;

Sample-2: The code bellow will show Hello World! too, but it will make the string modifiable

$str = 'Hello World!';
echo apply_filters( 'modify_str', $str );

Sample-3: If you use a filter hook (in a plugin or your functions.php file), the code I wrote in Sample-2 will show HELLO WORLD!

function modify_hello_world( $str ){
    return strtoupper( $str );
add_filter( 'modify_str', 'modify_hello_world' );

Hope it makes sense.

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment