When developing themes and plugins it is sometimes neccesary to add some functionality to some hook using conditional statements.

Example:

function my_custom_function() {
    if( is_home()) {
       <---what should the function do--->
    }
}

 add_action( 'some_hook', 'my_custom_function' );

To my understanding, whenever any other condition exists (is_home return false), the content of the function is not executed, however the function is executed, although it is “empty”. This means that an empty function is passed to the hook. This is the way that all examples are shown in the codex using conditional tags.

I do understand that this is safe to do so, and it should not have any significant impact on load times (if there is any impact on load time at all).

I have been thinking, the same piece of code, as per example, can be written as follow

if( is_home()) {
   function my_custom_function() {
     <---what the function should do--->
   }

  add_action( 'some_hook', 'my_custom_funtion' );

}

This will completely skip everything if is_home returns false.

I don’t mind using any of these two methods. But what I want to know, because of the first example been extensively used, are there any coding standard that states that this is the correct method to use, or is this rather the prevered way according to wordpress developers, or just personal preference.

5 s
5

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 Reply

Your email address will not be published. Required fields are marked *