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

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 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.

Solution 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);

Solution 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.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

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 Reply