Last active
October 22, 2023 23:14
-
-
Save markjaquith/b752e3aa93d2421285757ada2a4869b1 to your computer and use it in GitHub Desktop.
Version of `add_filter()` for WordPress that only runs once
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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
See @Rarst's Advanced Hooks!