Actions, functions and conditionals

WordPress coding standards for PHP does not state anything about this, and there is no other standard, so it’s up to developers to choose one way or another.

I have to say that the 2 methods have different approaches; while the first contains conditional logic, the second is a conditional function declaration, which means that if you try to call the function, you obtain a fatal error.

Even if using the first method, where the function runs (with a very minimal impact on performance that is irrelevant and lost in the application load), it is a better approach to use it, because when using the second method, the business logic of your application is moved from functions to the file parsing.

Moreover, you should consider there is a third way you’ve not mentioned:

function my_custom_function() {
    // what the function should do
}

if ( is_home() ) {
    add_action( 'some_hook', 'my_custom_function' );
}

The benefit to this approach is more perceptible when you use OOP programming: in that case, class conditional declaring makes no sense (and method conditional declaring is not possible at all), but it makes a lot of sense running tasks only under specific conditions (hooks firing).

Leave a Comment