amritansh
9/26/2017 - 5:48 AM

Understanding the concept of action and filter in wordpress

Understanding the concept of action and filter in wordpress

##Now understand this code:-

  1. First we create a sample array of fruits with two key value pair.
  2. Now seconds line shows that to modify this array we create a filter which we name as amrt_cust.
  3. Simple by passing the "name" as first param & "variable to modify" on second param.
  4. So think it as some variable whose value is required at many points and we want to chnage it at some certain actions, so we need to accomplish this using filters in wordpress.
  5. Now when we created a filter, lets use it and modify the data.
  6. we going to use add_filter() for this, this function takes the name of already created filter as first param and callback function as second.
  7. If you see in the defination of callback function we use one argument. Now the logic is, no. of arguments can be used is equal to the no. of variable to change in apply_filter() function.
  8. So in this callback function what we did, change the value of second key in this array. Now understand this , when we changed the value, it got change globelly. Which means in your one php execuation the chnaged value will get procceded as $array.

Thanks!

$array = array(
    0 => 'orange',
    1 => 'banana'
);

apply_filters('amrt_cust', $array);
function applynow($array) {
    $array[1] = 'grapes';
    print_r($array);
    die;
}

add_filter('amrt_cust', 'applynow');