Skip to content

Instantly share code, notes, and snippets.

@joemcgill
Last active March 4, 2020 01:43
Show Gist options
  • Save joemcgill/73a062a74af19207435517cc2dd8d836 to your computer and use it in GitHub Desktop.
Save joemcgill/73a062a74af19207435517cc2dd8d836 to your computer and use it in GitHub Desktop.
Remove filters added from class instances on a specific hook.
class Test_Class {
public function __construct() {
add_filter( 'pre_get_posts', [$this, 'test_callback'] );
}
public function test_callback() {
wp_die( 'Hooked up.' );
}
}
$test = new Test_Class();
add_action( 'init', function () {
remove_class_filter( 'pre_get_posts', 'Test_Class', 'test_callback' );
}, 99 );
/**
* Removes a filter added from a class instance from a specified hook.
*
* @param string $hook The filter hook from which to remove the callback method.
* @param string $class_name The name of the class containing the method to remove.
* @param string $method_to_remove The name of the method to be removed.
* @param integer $priority Optional. The priority of the function. Default 10.
* @return bool Whether the function existed before it was removed.
*/
function remove_class_filter( $hook, $class_name, $method_to_remove, $priority = 10 ) {
global $wp_filter;
// Bail early if there are no callbacks on this filter.
if ( ! has_filter( $hook ) ) {
return false;
}
$callbacks = &$wp_filter[ $hook ]->callbacks;
// Exit if there aren't any callbacks for specified priority
if ( ! isset( $callbacks[ $priority ] ) || empty( $callbacks[ $priority ] ) ) {
return false;
}
// Loop through each filter for the specified priority, looking for our class & method
foreach ( $callbacks[ $priority ] as $callback ) {
// If the callback is not an array, skip it.
if ( ! is_array( $callback[ 'function' ] ) ) {
continue;
}
// If the callback matches the class and method we're looking for, remove it.
if (
$callback[ 'function' ][0] instanceof $class_name &&
$callback[ 'function' ][1] === $method_to_remove
) {
return remove_filter( $hook, array( $callback[ 'function' ][0], $callback[ 'function' ][1] ), $priority );
}
}
// We only get here if no filter was found.
return false;
}
@joemcgill
Copy link
Author

This is an example of a helper function that can be used to remove a filter that was added by a class instance that is not accessible along with a simplified test case to show how this would apply.

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