Implementing advanced add_* function wrappers

add_action() and add_filter() are major functions. However in some scenarios add one more function and hook it somewhere approach gets bulky and inconvenient.

I had determined for myself several use cases that can streamline code with wrappers on top of add_* functions. Things that are better handled with single-liner than extra function each and every time.

  1. Add arbitrary filter return. There is already __return_* functions but they are very limited by definition. Why not just pass what you want returned in filter. Saves from myriad function return_stuff(){return 'stuff';}

  2. Replace X with Y in filter. Saves from myriad function replace_stuff(){return str_replace();}

  3. Add action with arbitrary arguments. Actions fire with arguments, passed in hook. But sometimes you don’t care about that and just want ot run your function with your own arguments at specific hook. Saves from myriad function echo_stuff(){echo 'stuff'}; and more.

So…

  • Are there any other use cases you want and/or use in practice?

  • How would you implement such wrappers? There are a lot of possible approaches (closures, global variables to keep additional arguments, passing objects in callback, etc).

PS I have couple different implementations for (1) and (3) already and (as suggested) will post bits of my code some time later so I don’t spoil the fun. 🙂

Example

Current way:

add_filter('wp_feed_cache_transient_lifetime', 'change_transient_lifetime', 10);

function change_transient_lifetime($lifetime) {

    return 3600;
}

Wrapper:

add_filter_return('wp_feed_cache_transient_lifetime', 10, 3600);

5 s
5

For simple cases like quick one-liner returns one should remember that it’s possible to hook an anonymous function directly in the add filter call, e.g:

add_filter('some_filter_hook', function($v){return str_replace('..', '.', $v);});

add_action('some_action_hook', function(){echo '....';});

Leave a Comment