Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Version of `add_filter()` for WordPress that only runs once
<?php
/*
Use this just like `add_filter()`, and then run something that calls the filter (like
`new WP_Query`, maybe).
That's it. If the filter gets called again, your callback will not be.
This works around the common "filter sandwich" pattern where you have to remember to
call `remove_filter` again after your call.
*/
function add_suicidal_filter( $hook, $callback, $priority = 10, $params = 1 ) {
add_filter( $hook, function( $first_arg ) use( $callback ) {
static $ran = false;
if ( $ran ) {
return $first_arg;
}
$ran = true;
return call_user_func_array( $callback, func_get_args() );
}, $priority, $params );
}
@markjaquith

This comment has been minimized.

Copy link
Owner Author

@markjaquith markjaquith commented Dec 7, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.