Wordpress plugin functions: check if function exists
I'm developing a Wordpress site that relies on a plugin to be activated for the site to function properly.
The plugin has a few useful functions that I'm using in the site's template files. When the 开发者_开发问答plugin is active, everything works perfectly. If the plugin is deactivated, the content doesn't load.
Wrapping these functions in if(function_exists(...)
obviously fixes that, but I'm wondering if there's a cleaner way of doing that in Wordpress. Is there a function that can be placed in the theme's functions.php file that can check if these functions are available every time I call them, and if not provide a safe fallback without me having to wrap them in the function_exists()?
Thanks.
If you're only using it sparingly (1-2 times), use if( function_exists() )
. If you're calling the function several times through in different template files, I'd suggest using something like
In your functions.php
function mytheme_related_posts( $someparams = nil ) {
if( function_exists( 'related_posts' ) ) {
related_posts( $someparams );
} else {
echo 'Please enable related posts plugin';
}
}
Then use mytheme_related_posts()
in your template.
I think this is the most clear way. It prevents all problems. I think you can write a function instead which can check if these functions are available every time you call them, but I'm almost sure it can cause you more trouble and it burns more memory then simply using if(function_exist()). Don't forget the else branch and it will work fine.
If you want to check if a plugin is active then you should be using the is_plugin_active()
function - you can find the docs at: http://codex.wordpress.org/Function_Reference/is_plugin_active
You can then also use if(function_exists()) as well just to doubly make sure :)
精彩评论