Skip to content

Instantly share code, notes, and snippets.

@danchivz
Last active August 29, 2015 14:18
Show Gist options
  • Save danchivz/1017787a49e4e8c5e373 to your computer and use it in GitHub Desktop.
Save danchivz/1017787a49e4e8c5e373 to your computer and use it in GitHub Desktop.
WordPress Hook Debug. List functions attached on a specific action or filter
<?php
/**
* Wordpress Hook Debug
* List functions attached on a specific action or filter
* http://gist.github.com/danchivz
*
* Licensed under the MIT license.
*/
/**
* Wordpress is heavily based on actions and filter, so to have the right tool to inspect hooks is the need of every wordpress developer.
* This function returns an array of all the functions hooked on a specific action or filter. Each item will have function name ( callback syntax ),
* number of accepted arguments, path of the file where the hook is attached, as well as the line in code where the function is defined. Array is sorted in order of priority.
*
* Example ( for wp_head action hook ):
* add_action( 'wp_footer', function() {
* echo '<pre>'.print_r( list_hooks( 'wp_head' ), true ).'</pre>';
* });
*
* @param string $hook The name of the action or filter.
* @return array
*/
function list_hooks( $hook = '' ) {
global $wp_filter;
$hooks = isset( $wp_filter[$hook] ) ? $wp_filter[$hook] : array();
$hooks = call_user_func_array( 'array_merge', $hooks );
foreach( $hooks as &$item ) {
// function name as string or static class method eg. 'Foo::Bar'
if ( is_string( $item['function'] ) ) {
$ref = strpos( $item['function'], '::' ) ? new ReflectionClass( strstr( $item['function'], '::', true ) ) : new ReflectionFunction( $item['function'] );
$item['file'] = $ref->getFileName();
$item['line'] = get_class( $ref ) == 'ReflectionFunction'
? $ref->getStartLine()
: $ref->getMethod( substr( $item['function'], strpos( $item['function'], '::' ) + 2 ) )->getStartLine();
// array( object, method ), array( string object, method ), array( string object, string 'parent::method' )
} elseif ( is_array( $item['function'] ) ) {
$ref = new ReflectionClass( $item['function'][0] );
// $item['function'][0] is a reference to existing object
$item['function'] = array(
is_object( $item['function'][0] ) ? get_class( $item['function'][0] ) : $item['function'][0],
$item['function'][1]
);
$item['file'] = $ref->getFileName();
$item['line'] = strpos( $item['function'][1], '::' )
? $ref->getParentClass()->getMethod( substr( $item['function'][1], strpos( $item['function'][1], '::' ) + 2 ) )->getStartLine()
: $ref->getMethod( $item['function'][1] )->getStartLine();
// closures
} elseif ( is_callable( $item['function'] ) ) {
$ref = new ReflectionFunction( $item['function'] );
$item['function'] = get_class( $item['function'] );
$item['file'] = $ref->getFileName();
$item['line'] = $ref->getStartLine();
}
}
return $hooks;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment