Remove any action or filter in WordPress

Sometimes we need to remove actions or filters added via Themes or Plugins. To remove a action or filter check mekshq.com’s guide.

But sometimes that is not enough, sometimes some hooks are too stubborn to remove. In that case use davelavoie’s function to remove any action or filter. I’m just copy pasting the codes here.

/**
 * Remove Class Filter Without Access to Class Object
 *
 * In order to use the core WordPress remove_filter() on a filter added with the callback
 * to a class, you either have to have access to that class object, or it has to be a call
 * to a static method.  This method allows you to remove filters with a callback to a class
 * you don't have access to.
 *
 * @param string $tag         Filter to remove
 * @param string $class_name  Class name for the filter's callback
 * @param string $method_name Method name for the filter's callback
 * @param int    $priority    Priority of the filter (default 10)
 *
 * @return bool Whether the function is removed.
 */
if ( ! function_exists( 'remove_class_hook' ) ) {
	function remove_class_hook( $tag, $class_name = '', $method_name = '', $priority = 10 ) {
		global $wp_filter;
		$is_hook_removed = false;
		if ( ! empty( $wp_filter[ $tag ]->callbacks[ $priority ] ) ) {
			$methods     = wp_list_pluck( $wp_filter[ $tag ]->callbacks[ $priority ], 'function' );
			$found_hooks = ! empty( $methods ) ? wp_list_filter( $methods, array( 1 => $method_name ) ) : array();
			foreach( $found_hooks as $hook_key => $hook ) {
				if ( ! empty( $hook[0] ) && is_object( $hook[0] ) && get_class( $hook[0] ) === $class_name ) {
					$wp_filter[ $tag ]->remove_filter( $tag, $hook, $priority );
					$is_hook_removed = true;
				}
			}
		}
		return $is_hook_removed;
	}
}

Example Usage:

add_action( 'admin_menu', function() {
	remove_class_hook( 'admin_head', 'TIELABS_SETTINGS_POST', 'post_subtitle' );
});

If the class is namespaced then you must specify the namespace without root. Example:

add_action( 'init', function() {
    remove_class_hook( 'delete_attachment', 'JNews\AccountPage', 'disable_delete_attachment' );
});