Removing hooked filter / action method that doesn’t use static method

Static method is ideally better to be used as filter / action callback because it is easier to be added and removed. This is especially needed if third party plugin / theme might need to modify your registered callback for whatever reason:

class Thor {
  static function weapon() {
    echo 'hammer';

// Registering action callback
add_action( 'wp_footer', array( 'Thor', 'weapon' ) );

// Removing action callback
remove_action( 'wp_footer', array( 'Thor', 'weapon' ) );

However, you’ll find out that there are many plugins / themes that register filter / action callback without using static method like this:

class Thor {
  function __construct() {
    // Registering action callback; Mostly used if you need the class instance somehow on the method
    add_action( 'wp_footer', array( $this, 'catchphrase' ) );

  function catchphrase() {
    echo 'should have gone for the wp_head';
new Thor;

It is way trickier to remove this registered method callback because there’s no variable defined for the class instance. I forgot when and where did I learn this trick but i recall as long as you can access the global $wp_filter variable, you can still remove it:

function remove_thor_catchphrase() {
  global $wp_filter;

  // Loop the callbacks of known action: registered callback grouped by priority
  foreach ( $wp_filter['wp_footer']->callbacks as $priority => $hooks ) {

    // Loop the groups callbacks; you'll get registered callback that can be used as reference as key and the callback setting as value
    foreach ( $hooks as $registered_callback => $callback_setting ) {
      $callback_function = $callback_setting['function'];

      // Make sure to find out what we're looking for by evaluating the callback setting
      if ( 'object' === gettype( $callback_function[0] ) && 'Thor' === get_class( $callback_function[0] ) && 'catchphrase' === $callback_function[1] ) {
        // Removing action callback once we're sure that this is the one that we want to remove
        remove_action( 'wp_footer', $registered_callback, $priority );

Note: directly modifying global WordPress variable might not be preferable (some code sniffer even might warn you); However if you desperately need it, here’s one way to do it.

Leave a Reply

Your email address will not be published. Required fields are marked *