• Well, am having a very hard time understanding the difference between Actions and Filters. I do use actions in my code, but am a rookie and I don’t know even a slightest bit of Filters.

    I have been to codex, and various sites by NickTheGeek, BillErickson, Gary Jones etc, but no vein.

    If you can tell me in simple words, with example that what basically is and difference between actions, filters and hooks.

    Thanks a ton.

Viewing 5 replies - 1 through 5 (of 5 total)
  • Filters take content, alter it, and return that content back to the function running the filter. Conceptually they are sort-of like PHP’s string functions– preg_replace(...) or substr(...), for example.

    Actions don’t alter content in that way. Actions do things like alter global settings. They don’t process content inline.

    https://ottopress.com/2011/actions-and-filters-are-not-the-same-thing/

    Thread Starter Vajrasar Goswami

    (@vajrasar)

    So when am using X filter – does that mean I have to write who X fuctions once again to suit my need?

    Like if X is taking ‘a’ and summing that with ‘b’ to get ‘a+b’ and returning ‘c’. And if I want it to return ‘c+2’ -> then do I have to write whole function to change it or just return final result with ‘+2’ ?

    Moderator Samuel Wood (Otto)

    (@otto42)

    www.ads-software.com Admin

    An action is a defined place in the code where you can insert your own code. So if the line do_action('init') is called, then you can hook in your own code with add_action('init','my_function'); and your function will get run at that point in the code.

    A filter is like an action, but you’re expected to be acting on some variable, possibly modifying it, and returning the result.

    For example, say I have this code:

    $value = 5;
    $value = apply_filters( 'value_adjuster', $value );

    That code takes whatever $value is (in this case, five), and runs it through the “value_adjuster” filter. So if I want to modify that value, I can use a filter to do it like so:

    add_filter( 'value_adjuster', 'my_filter' );
    function my_filter( $original_value ) {
      $new_value = $original_value + 5;
      return $new_value;
    }

    Now $value will be 10 after the apply_filters function runs.

    That help any?

    Thread Starter Vajrasar Goswami

    (@vajrasar)

    @otto, thanks man. You don’t know how much you’ve helped me with this one. Thumbs Up!

    Thread Starter Vajrasar Goswami

    (@vajrasar)

    Just one last thing, So you mean to say that as in that example – I can use any filter/function instead of value_adjuster to suit my need, right!

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Actions, Filters and Hooks’ is closed to new replies.