Skip to content

Instantly share code, notes, and snippets.

@BrianHenryIE
Last active November 24, 2021 23:07
Show Gist options
  • Save BrianHenryIE/485ca2e2ecb31413c2308d1774a50218 to your computer and use it in GitHub Desktop.
Save BrianHenryIE/485ca2e2ecb31413c2308d1774a50218 to your computer and use it in GitHub Desktop.
Unhook a closure from a WordPress action by using the class the closure binds to to compare.
<?php
/**
* Unhook a closure from a WordPress action by using the class the closure binds to to compare.
*/
$action_name = 'admin_notices';
$priority = 10;
$expected_class = MyClass::class;
$hooked = (array) $GLOBALS['wp_filter'][$action_name][$priority];
foreach( $hooked as $action ) {
$function = $action['function'];
// If it's a string, it's a function.
if( is_string( $function )) {
continue;
}
// If it's an array then it's an array of [class,function_name].
if( is_array( $function ) ) {
continue;
}
try {
$reflection = new ReflectionFunction( $function );
} catch ( \ReflectionException $e ) {
continue;
}
$bound_to = $reflection->getClosureThis();
if( $bound_to instanceof $expected_class) {
remove_action( $action_name, $function, $priority );
}
}
@Preciousomonze
Copy link

Nice, @BrianHenryIE , line 38, 'admin_notices' should be replaced with $action_name right?

@BrianHenryIE
Copy link
Author

Yes, thank you. That's updated now.

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