Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
An example showing why you don't remove a WP filter/action when it's currently being called.
<?php
/*
* A basic proof of concept showing how you shouldn't remove an action/filter when it's currently being called
* The $array is the basic structure of $GLOBALS['wp_filter'][ $tag ] while the do/while loop is how WordPress
* loops through the current action/filter being called.
*/
$array = [
1 => ['1-1'],
10 => [ '10-1', '10-2', '10-3' ],
];
do {
foreach ( (array) current($array) as $the_ ) {
/* Check we are running 1-1 and then mimic the remove_action() function */
if ( '1-1' == $the_ ) {
/* Removes the array from priority 1 */
unset( $array[1][0] );
/*
* This section is why you should't remove actions/filters while being run.
* WordPress will remove the entire priority if it is empty
*
* Excerpt from remove_filter():
*
* if ( empty( $GLOBALS['wp_filter'][ $tag ][ $priority ] ) ) {
unset( $GLOBALS['wp_filter'][ $tag ][ $priority ] );
* }
*
* Unsetting the current array key shifts the array pointer down to 10
*
*/
unset( $array[1] );
}
/* This will output 1-1 because $the_ is a copy of the array value and is set at the start of the loop */
echo $the_ . '<br>';
}
/* There won't be a next array key because it's already at priority 10 and all the priority 10 functions will be skipped over */
} while ( next($array) !== false );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment