Skip to content

Instantly share code, notes, and snippets.

@synthetiv
Forked from danielbachhuber/wp-hook-command.php
Last active August 26, 2016 20:59
Show Gist options
  • Save synthetiv/d635a105546c8dcc7a68aef09fdc6e31 to your computer and use it in GitHub Desktop.
Save synthetiv/d635a105546c8dcc7a68aef09fdc6e31 to your computer and use it in GitHub Desktop.
WP-CLI command to list callbacks registered to a given action or filter
<?php
if ( class_exists( 'WP_CLI' ) ) :
/**
* List callbacks registered to a given action or filter.
*
* <hook>
* : The key for the action or filter.
*
* [--format=<format>]
* : List callbacks as a table, JSON, or CSV. Default: table.
*
* EXAMPLES
*
* wp --require=wp-hook-command.php hook wp_enqueue_script
*/
$hook_command = function( $args, $assoc_args ) {
global $wp_filter;
$assoc_args = array_merge( array(
'format' => 'table',
), $assoc_args );
$hook = $args[0];
if ( ! isset( $wp_filter[ $hook ] ) ) {
WP_CLI::error( "No callbacks specified for {$hook}." );
}
$callbacks_output = array();
foreach( $wp_filter[ $hook ] as $priority => $callbacks ) {
foreach( $callbacks as $callback ) {
if ( is_array( $callback['function'] ) ) {
if ( is_object( $callback['function'][0] ) ) {
$class = get_class( $callback['function'][0] );
} else {
$class = $callback['function'][0];
}
$method = $callback['function'][1];
$function_name = "$class->$method";
$reflection = new ReflectionClass( $class );
$definition = $reflection->getFileName() . ':' . $reflection->getMethod( $method )->getStartLine();
} else {
$function_name = $callback['function'];
$reflection = new ReflectionFunction( $function_name );
$definition = $reflection->getFileName() . ':' . $reflection->getStartLine();
}
$callbacks_output[] = array(
'function' => $function_name,
'priority' => $priority,
'accepted_args' => $callback['accepted_args'],
'definition' => preg_replace( '#^' . ABSPATH . '#', '', $definition ),
);
}
}
WP_CLI\Utils\format_items( $assoc_args['format'], $callbacks_output, array( 'function', 'priority', 'accepted_args', 'definition' ) );
};
WP_CLI::add_command( 'hook', $hook_command );
endif;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment