WordPress.org

Ready to get started?Download WordPress

Forums

Actions, Filters and Hooks (6 posts)

  1. Vajrasar Goswami
    Member
    Posted 2 years ago #

    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.

  2. s_ha_dum
    Member
    Posted 2 years ago #

    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.

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

  3. Vajrasar Goswami
    Member
    Posted 2 years ago #

    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' ?

  4. Samuel Wood (Otto)
    Tech Ninja
    Posted 2 years ago #

    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?

  5. Vajrasar Goswami
    Member
    Posted 2 years ago #

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

  6. Vajrasar Goswami
    Member
    Posted 2 years ago #

    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!

Topic Closed

This topic has been closed to new replies.

About this Topic