Skip to content

Instantly share code, notes, and snippets.

@tux255
Forked from markjaquith/suicidal-filter.php
Created December 8, 2016 09:54
Show Gist options
  • Save tux255/99256f2890f05d3bff0fabe0bade881a to your computer and use it in GitHub Desktop.
Save tux255/99256f2890f05d3bff0fabe0bade881a to your computer and use it in GitHub Desktop.
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 );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment