Created
March 9, 2017 11:19
-
-
Save vishalbasnet23/5f74df4c800681199ab0246bc037d1d5 to your computer and use it in GitHub Desktop.
Remove Filters of class files with out invoking class.
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 | |
function remove_class_filter( $tag, $class_name = '', $method_name = '', $priority = 10 ) { | |
global $wp_filter; | |
// Check that filter actually exists first | |
if ( ! isset( $wp_filter[ $tag ] ) ) return FALSE; | |
if ( is_object( $wp_filter[ $tag ] ) && isset( $wp_filter[ $tag ]->callbacks ) ) { | |
// Create $fob object from filter tag, to use below | |
$fob = $wp_filter[ $tag ]; | |
$callbacks = &$wp_filter[ $tag ]->callbacks; | |
} else { | |
$callbacks = &$wp_filter[ $tag ]; | |
} | |
// 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( (array) $callbacks[ $priority ] as $filter_id => $filter ) { | |
// Filter should always be an array - array( $this, 'method' ), if not goto next | |
if ( ! isset( $filter[ 'function' ] ) || ! is_array( $filter[ 'function' ] ) ) continue; | |
// If first value in array is not an object, it can't be a class | |
if ( ! is_object( $filter[ 'function' ][ 0 ] ) ) continue; | |
// Method doesn't match the one we're looking for, goto next | |
if ( $filter[ 'function' ][ 1 ] !== $method_name ) continue; | |
// Method matched, now let's check the Class | |
if ( get_class( $filter[ 'function' ][ 0 ] ) === $class_name ) { | |
// WordPress 4.7+ use core remove_filter() since we found the class object | |
if( isset( $fob ) ){ | |
// Handles removing filter, reseting callback priority keys mid-iteration, etc. | |
$fob->remove_filter( $tag, $filter['function'], $priority ); | |
} else { | |
// Use legacy removal process (pre 4.7) | |
unset( $callbacks[ $priority ][ $filter_id ] ); | |
// and if it was the only filter in that priority, unset that priority | |
if ( empty( $callbacks[ $priority ] ) ) { | |
unset( $callbacks[ $priority ] ); | |
} | |
// and if the only filter for that tag, set the tag to an empty array | |
if ( empty( $callbacks ) ) { | |
$callbacks = array(); | |
} | |
// Remove this filter from merged_filters, which specifies if filters have been sorted | |
unset( $GLOBALS['merged_filters'][ $tag ] ); | |
} | |
return TRUE; | |
} | |
} | |
return FALSE; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment