Last active
November 11, 2019 05:31
-
-
Save LachlanArthur/d9d83ef22e57d16bfb40568ffc26fe4b to your computer and use it in GitHub Desktop.
WordPress - Unhook a class method from an action or filter, even if you don't have a reference to the class instance.
This file contains hidden or 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 | |
/** | |
* Removes hooks that trigger a certain class method, | |
* even if you don't have a reference to the class instance. | |
* | |
* @global \WP_Hook[] $wp_filter | |
* @param string $filter | |
* @param string $class | |
* @param string $method | |
* @param int $priority | |
* @param int $args | |
* @return int How many filters were unhooked | |
*/ | |
function unhook_class_method( $filter, $class, $method, $priority = null ) { | |
global $wp_filter; | |
$to_remove = []; | |
foreach ( $wp_filter[ $filter ]->callbacks as $hook_priority => $callbacks ) { | |
if ( $priority !== null && $priority !== $hook_priority ) { | |
continue; | |
} | |
foreach ( $callbacks as $callback ) { | |
if ( | |
is_array( $callback[ 'function' ] ?? null ) && | |
is_object( $callback[ 'function' ][ 0 ] ?? null ) && | |
get_class( $callback[ 'function' ][ 0 ] ) === $class && | |
( $callback[ 'function' ][ 1 ] ?? null ) === $method | |
) { | |
$to_remove[] = [ $filter, $callback[ 'function' ], $hook_priority ]; | |
} | |
} | |
} | |
foreach ( $to_remove as $args ) { | |
call_user_func_array( 'remove_filter', $args ); | |
} | |
return count( $to_remove ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment