Skip to content

Instantly share code, notes, and snippets.

@markjaquith
Last active October 22, 2023 23:14
Show Gist options
  • Save markjaquith/b752e3aa93d2421285757ada2a4869b1 to your computer and use it in GitHub Desktop.
Save markjaquith/b752e3aa93d2421285757ada2a4869b1 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 );
}
@markjaquith
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment