I noticed a lot of developers of WordPress themes would use this in functions.php
if (function_exists('register_nav_menus')) {
register_nav_menus (array('primary' => 'Header Navigation'));
}
For me, I alwayse use add_action for every function I am using in functions.php
So, the above would be written as:
add_action('init', 'my_register_nav_menus');
function my_register_nav_menus() {
register_nav_menus (array('primary' => 'Header Navigation'));
}
I have two questions:
-
Why use the if statement in the first method?
-
Which one is the correct way?
Checking to see if built in WordPress functions exist before calling them is for backward compatibility which IMHO is not needed.
So if you see
if ( function_exists( 'register_nav_menus' ) )
the theme author is supporting versions earlier than 3.0.You still sometimes see
if ( function_exists( 'dynamic_sidebar' ) )
Why? I couldn’t tell you because dynamic_sidebar was introduced in 2.2.Another reason to use it is to make your theme or plugin pluggable. A pluggable function is one that can be overridden in a child theme or another plugin.
This is done on the definition not the call and you use the ! operator to make sure it doesn’t already exist before you define it.
When this is done a child theme or other plugin can override that function with there own.
The
function_exists
function is not an other way to load the function likeadd_action
its for check your code to see that there are no other function with that same name so it will not break your code. From php.net:If you have the same function twice in your code it will break, thats why you prefix Your function with something else than wp_.
Read more: http://php.net/manual/en/function.function-exists.php
you can use http://php.net/function_exists
OR if you want to see the all function available, so you also print all,
print on page and you can search that function if it is not found on list means it is not available to use.
you may need to activate extension for particular library.
php.net defines this as
I have to agree with Michelle in usage in that you [sh]ould only use the check for something similar to type cast checking; so you would be looking for if a function existed (on that page or from anything called on that page/file reference) so then you would know if is safe to run another function or parse some template HTML possibly.
As someone mentioned it is used commonly to check if your file/theme (using WordPress) is able to run your needed request. I have used it for checking if a theme has a specific template part.
if ( function_exists( 'register_sidebar' ) ) {
get_sidebar();
}
function_exists
should be used after the function name in a theme not before.This checks to make sure the plugin is active before outputting a function and/or markup otherwise you might get a error like call to undefined function.