Skip to content

Instantly share code, notes, and snippets.

@robertuniqid
Created April 14, 2020 20:03
Show Gist options
  • Save robertuniqid/fdb9effd895c0ce27d73a468b6231e36 to your computer and use it in GitHub Desktop.
Save robertuniqid/fdb9effd895c0ce27d73a468b6231e36 to your computer and use it in GitHub Desktop.
WordPress - Example remove action registered with $this object reference.
<?php
class Foo {
public function __construct() {
add_action( 'init', [ $this, '_bar' ] );
}
public function _bar() {
exit( "Request Blocked, action was not removed" );
}
}
new Foo(); // or $bar = new Foo();
// essentially, $bar would not be a variable accessible by the code below, because it was defined in a totally different namespace or environement.
global $wp_filter;
if( isset( $wp_filter[ 'init' ] ) ) {
$callbacks = $wp_filter[ 'init' ]->callbacks;
// We assume that the priority will always be 10, in case the priority is not static for whatever reason, we need to loop trough all the priorities.
if( isset( $callbacks[ 10 ] ) ) {
foreach( $callbacks[ 10 ] as $callback_index => $callback ) {
// Normally this would not happen, but lets assume we need to do integrity checks.
if( !isset( $callback['function' ] ) )
continue;
// If it's not an array, it's a function or closure, and in this example we don't take closures in the digging, but essentially those are even nastier.
if( !is_array( $callback['function' ] ) )
continue;
if( !( $callback['function' ][ 0 ] instanceof Foo ) )
continue;
// In this case, we remove everything, but you would target specifically for $callback['function' ][ 1 ] by simple checking if $callback['function' ][ 1 ] === '_bar'
remove_action( 'init', [ $callback['function' ][ 0 ], $callback['function' ][ 1 ] ] );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment