How apply_filters work in WordPress?

Yes the apply_filters() hook is bit confusing at first when you encounter it.
I’ll try my best to explain this:

first you need to know that filter hooks allow you to change data before displaying or storing data.

Lets take an example

function list_array(){
  $arr_name = ['val1', 'val2', 'val3'];
  return $arr_name;
}

as you can see above function just returns an array and consider this code was in your plugin and you want other developer to modify the default array. That’s where apply_filters() hook comes in handy

function list_array(){
  $arr_name = ['val1', 'val2', 'val3'];
  $arr_name = apply_filters( 'hook_identifier', $arr_name);
  return $arr_name;
}

now the ‘hook_identifier’ can be used to modify the array values, like

function add_extra_val( $arr ){
  $extra_val = ['extraval1','extraval2','extraval3']; //remember you are adding elements to array
  $arr = array_merge($extra_val, $arr);
}
add_filter('hook_identifier', 'add_extra_val');

You see the add_extra_val function takes one array ( as every filter hook, ) as an argument and then extra values are added to that array and then returned.

so what exactly did apply_filters() hook did?

it is calling all the functions ( in this case ‘add_extra_val’ ) that have been added to the hook ( in this case ‘hook_identifier’ ) at that point in the code base ( in this case when $arr_name = apply_filters( ‘hook_identifier’, $arr_name) ).

This is it. hope you understand now.

Leave a Comment