WooCommerce subscriptions speed up from external plugin

WooCommerce subscriptions speed

If you are running a WooCommerce subscriptions website you might avoid front-end delays by using proper caching. But in the admin you will still encounter issues with large databases and not only.

Using the Query monitor plugin I found that the class used by WooCommerce subscriptions to check for deprecated hooks is actually doubling the loading times for some of the pages. The class “WCS_Dynamic_Hook_Deprecator” is adding an action on the “all” hook. The “all” hook should never be used unless really needed ( this is a real case where this is needed ).

Removing the action

The main problem when trying to remove the action is that it is adding using an anonymous function in a class instance:

add_filter( 'all', array( &$this, 'check_for_deprecated_hooks' ) );

As explained in this awesome WordPress Stackexchange answer, because the function is anonymous WP generates a name for it using the _wp_filter_build_unique_id function. This means we can find the hook and remove it using the $GLOBALS variable.

It’s much easier than it sounds when using the function below ( from the same answer mentioned above ):

if ( ! function_exists( 'remove_anonymous_object_filter' ) )
{
   /**
    * Remove an anonymous object filter when a class uses $this
    *
    * @param  string $tag    Hook name.
    * @param  string $class  Class name
    * @param  string $method Method name
    * @return void
    */
   function remove_anonymous_object_filter( $tag, $class, $method )
   {
      $filters = $GLOBALS['wp_filter'][ $tag ];
      if ( empty ( $filters ) )
      {
         return;
      }
      foreach ( $filters as $priority => $filter )
      {
         foreach ( $filter as $identifier => $function )
         {
            if ( is_array( $function)
                 and is_a( $function['function'][0], $class )
                     and $method === $function['function'][1]
            )
            {
               remove_filter(
                  $tag,
                  array ( $function['function'][0], $method ),
                  $priority
               );
            }
         }
      }
   }
}

Add this as a stand-alone plugin or in your theme’s “functions.php” file. Afterwards you can remove the WooCommerce Subscriptions hook using:

// remove the hook deprecator check to speed up woocommerce subscriptions
remove_anonymous_object_filter('all', 'WCS_Dynamic_Hook_Deprecator', 'check_for_deprecated_hooks');

Obviously you can use this function for any other situation in which a class assigns an anonymous function to a hook.