Understanding apply_filters

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']);

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

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

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x