I’ve been sharing a lot lately about adding menu items and widgets to your dashboard. In many of these cases I’m tapping into specific functions from other plugins. So what happens to my website if I stop using that plugin or deactivate it for some reason? It crashes or throws all kinds of ugly errors, that’s what happens. And neither you or your visitors want to see that. But don’t fret, there is a real simple way to “crash-proof” your website in these instances.
[php]
if ( function_exists( ‘SOME FUNCTION NAME’ ) ) { YOUR CODE HERE }
[/php]
You should always use this check if including a function into your theme or plugin from another plugin. What is does is check to see if the function you are mentioning is a registered function. If it is, the script will continue to run as normal. If not, the script will not proceed. That way if you deactivate to remove the plugin altogether your site will continue to run fine, it will just exclude that particular functionality.
The function_exists call can be used in a variety of instances but sometimes you want to build a dependency upon another plugin completely. For instance, as long as another plugin is active, here is a bunch of things that I want to do to extend it further. WordPress has the perfect solution for these instances.
[php]
if ( is_plugin_active( ‘ninja-newsletters/ninja-newsletters.php’ ) ) { YOUR CODE HERE }
[/php]
In my example above I had a bunch of stuff I wanted to do if my Ninja Newsletters plugin was active. All it needs is the name of the main plugin file. In my case the file is in a directory named “ninja-newsletters” and the files is “ninja-newletters.php” so my complete check is “ninja-newsletters/ninja-newsletters.php”. Pretty easy.
Which One Should I Use
The answer is, it depends. It comes down to performance and testing.
function_exists will basically look through every function that is defined within your site until it finds the one you told it to check for. On my site I currently have 6090 defined functions. If you end up doing this a lot on a single page, I’ve not tested this, I could see it starting to slow down the site a bit.
is_plugin_active technically is meant only for your WordPress admin. You can use it on the front end but you would need to include plugin.php before calling the function. The advantage that I see in using this method is that the script doesn’t have to look through a long list of functions like a needle in a haystack to see if a particular function is defined. You tell it exactly what should be active and where it is. The script doesn’t have to find anything.
Of course all of this can depend on other variables so choose what you think is the best option for you and always test your work and see how it’s working efficiently enough for you.
Leave a Reply