Running a function without filters in WordPress

A simple snippet to run a piece of code without filters.

Unfiltered freedom

Running any piece of code WordPress is supposedly running filters and actions on is not a great idea but the need might arise sometimes.
So here is a function to have a callback run without any filters or actions hooked in the code

function without_filters( $callback, $whitelist = array() ) {
    if (!is_callable($callback)) {
        throw new InvalidArgumentException('Callback must be callable');
    }

    global $wp_filter, $merged_filters;

    // Save filters and actions state
    $wp_filter_backup      = $wp_filter;
    $merged_filters_backup = $merged_filters;

    $whitelist             = array_combine( $whitelist, $whitelist );
    $wp_filter             = array_intersect_key( $wp_filter, $whitelist );
    $merged_filters        = array_intersect_key( $merged_filters, $whitelist );

    $exit = call_user_func( $callback );

    // Restore previous state
    $wp_filter      = $wp_filter_backup;
    $merged_filters = $merged_filters_backup;

    return $exit;
}

and use it like this

// function callback
without_filters('my_function');

// closure callback
$value = without_filters(function(){
    $default = 'foo';
    return apply_filter('my_filter', $default);
});

// instance method callback
without_filters(array(my_object,'my_method'));

// static method callback
without_filters(array('My_Class','my_static_method'));

The function comes with a whitelisting possibility to allow some filters to stay hooked

function my_function(){
    // if something's hooked here it will still fire
    do_action('action_one');
    // nothing will be hooked here
    do_action('action_two'); 

     // if something is filtering here it will still filter
    $out = apply_filter('filter_one', 'foo');

    // nothing will filter here
    return apply_filters('filter_two', 'bar: ' . $out);

}

$value = without_filters('my_function',array('action_one','filter_one'));