Skip to content

Instantly share code, notes, and snippets.

@mcaskill
Forked from westonruter/01-common-example.php
Last active January 18, 2019 17:09
Show Gist options
  • Save mcaskill/ec3719480399ff97b088e02de737dd06 to your computer and use it in GitHub Desktop.
Save mcaskill/ec3719480399ff97b088e02de737dd06 to your computer and use it in GitHub Desktop.
WordPress \ Hooks : Temporarily disable hooks while executing a given callback.
<?php
/**
* Call the callback with one or all handlers disabled for the given action or filter.
*
* Temporarily disables the specified hook, or all hooks, from a specified filter or action
* before calling $callback.
*
* @link https://gist.github.com/westonruter/6647252
*
* @global array $wp_filter Stores all of the filters.
*
* @param callable $callback The callable to be called while the filter is disabled.
* @param string $tag The filter to remove hooks from.
* @param callable|null $handler The callback to be removed from running when the filter is applied.
* @return mixed Returns the return value of the callback.
*/
function without_filters( callable $callback, $tag, $handler = null )
{
global $wp_filter;
if ( $handler !== null ) {
return without_filter( $callback, $tag, $handler );
}
$wp_hook = null;
if ( isset( $wp_filter[ $tag ] ) && $wp_filter[ $tag ] instanceof WP_Hook ) {
$wp_hook = $wp_filter[ $tag ];
unset( $wp_filter[ $tag ] );
}
$retval = call_user_func( $callback );
if ( isset( $wp_hook ) ) {
$wp_filter[ $tag ] = $wp_hook;
}
return $retval;
}
/**
* Call the callback with one or all handlers disabled for the given action or filter.
*
* Temporarily disables the specified hook and filter or action before calling $callback.
*
* @link https://gist.github.com/westonruter/6647252
*
* @param callable $callback The callable to be called while the filter is disabled.
* @param string $tag The filter to remove hooks from.
* @param callable $handler The callback to be removed from running when the filter is applied.
* @return mixed Returns the return value of the callback.
*/
function without_filter( callable $callback, $tag, $handler )
{
$priority = has_filter( $tag, $handler );
if ( false !== $priority ) {
remove_filter( $tag, $handler, $priority );
}
$retval = call_user_func( $callback );
if ( false !== $priority ) {
// For array_slice(), can't use NULL since cast to integer
$accepted_args = PHP_INT_MAX;
add_filter( $tag, $handler, $priority, $accepted_args );
}
return $retval;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment