I know that how do_action works in WordPress.

function foobar_func( $atts ){
    // Action hook before any output!
    do_action( 'dr_before_get_qod_text' );

    echo "foo and bar";

add_shortcode( 'foobar', 'foobar_func' );

If I have a similar code, I can display "ABC" before displaying "foo and bar" using following code.

function display_abc() {
   echo "ABC";
add_action( 'dr_before_get_qod_text', 'display_abc');

But I can't understand how apply_filters work. Can you please give me a practical example?


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.

| improve this answer | |
  • Thanks, great explanation.. Is this applies for only modify object or arrays? Or are there more things? – I am the Most Stupid Person Jul 19 '18 at 8:50
  • as I said filter hooks are used to modify data and data can be any valid php data type. I choose array for demonstration purpose. – maverick Jul 19 '18 at 8:56
  • Thanks.... Just one question..... Do you know pre_get_posts . This hook is called after the query variable object is created, but before the actual query is run. The pre_get_posts action gives developers access to the $query object by reference This should be filter as I think? but why it implement as a action – I am the Most Stupid Person Jul 19 '18 at 9:07
  • Visit: wpshout.com/practical-uses-pre_get_posts for more information. – maverick Jul 19 '18 at 9:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.