How to restrict actions and filters “properly” by conditions

There is no real difference between the two methods.
When using method A, only the hooking is bound to the condition (i.e., the function is defined no matter what), while in method B the definition of the function as well as the hooking is.

Another thing is the following method (which you did not include):

function my_hooked_function() {
    if (! current_user_can('administrator')) {
        $some_var="some value";
        some_function($some_var);
    }
} // function my_hooked_function

add_action('widgets_init', 'my_hooked_function');

Since the complete condition can already be evaluated outside the function (i.e., directly in your functions.php file) method A/B should be preferred. Otherwise you would hook your function every time and for all users, while it is being used by administrators only.

There are, however, conditions, which cannot be put (i.e., evaluated) outside the hooked function, as some variable and/or object that is utilized in the condtion is not yet defined/accessible. In such a case you have to put the condition inside the function (as shown in this answer).

An example:

// NOT working
if (is_front_page())
    add_action('shutdown', function() { echo 'Front'; });

// WORKING
add_action('shutdown', function() { if (is_front_page()) echo 'Front'; });

Leave a Comment