Safeguard Your WordPress Themes with function_exists()

WordPress is great. At its core, it can run your basic website and blog. With the addition of plugins, WordPress becomes a powerhouse of functionality.

Need a feature that doesn’t come right out of the box? You don’t have to build it yourself. No, there’s a plugin for that. From e-commerce, to forums, to members-only sites and beyond, WordPress does it all. With 36,787 plugins at the time of this writing, there’s no limit to the number of things you can do.

It’s no wonder WordPress powers a fifth of all the web.

With Great Power Comes Great Responsibility

So you’ve installed a bunch of plugins and tied them into your theme. You’re calling functions provided by the plugins in your theme’s code and your website is awesome. Congrats.

But what happens if one of your plugins breaks, gets updated and deprecates the functions you’re calling, or you have to deactivate a plugin to solve a temporary issue?

Well, you better go throughout your theme files and remove all instances of those plugin-dependent functions first. (Then put them all back when you’re done.) Otherwise you’ll get errors on your website, or the website might not work at all.

There’s got to be a better solution for when using hand-coded functionality in your theme that relies on a plugin! And there is.

Safeguard Solution

In order to call functions that your plugins provide you, and not rely on them always being there for your site to work, you’ll need to add just a couple lines of code. By using function_exists() we can check for a function before we call it, thereby avoiding any errors when it doesn’t.

Around each block of plugin-dependent code, wrap the following if() statement.

if( function_exists( 'plugin_function_name' ) ) {
    ...dependent code goes here...
}

Replace plugin_function_name with the name of the function you’re referencing from your plugin.

Whenever the plugin is activated (and the function exists) your code will execute. If your plugin isn’t installed, activated, and including the functions you need, your code will be skipped and the rest of the site will be built, sans plugin-specific content.

Now you can rest easy knowing you’ve built a solid theme that utilizes some awesome plugins but doesn’t rely on them.

More than Just WordPress

Keep in mind, function_exists() is a PHP function not a WordPress function, so this can be applied to any CMS that uses plugins or code that may or may not be available at all times. Use it to be smart everywhere you code in PHP.