Handling error when WordPress plugin functions are not available

When we build a WordPress theme, sometime we need want to add more features using WordPress plugin. For example, we want to display commenter’s avatar from Gravatar service. Because we (as the theme creator) want to make our theme can handle Gravatar plugin by default, we directly put plugin function inside our theme file — to be more spesific inside comments.php.
If we share our theme (someone uses our theme), and his/her WordPress installation does not have Gravatar plugin installed, the theme might be broken. There will be an error. Single page (where the gravatar/comment should appear) will stop loading. Why? Because there is a gravatar plugin tag/function, but the plugin is not available.

Another thing, you downloaded a free theme, and you want to add gravatar function by yourself. So, you downloaded the Gravatar plugin, put plugin tag, and voila! All works. But when this plugin is deactivated (probably when you upgrade your WordPress installation) and you forgot to activate it again, your theme might nor working well. So, what’s the solution? It’s pretty simple: use the conditional tags. Okey, we’ll use Gravatar plugin as the example.

According to the documentation, you need to put <img src="<?php gravatar("R", 40, "http://path/to/gravatar_default.png"); ?>" alt="" /> in your comment template.
Sometime, we want to put it inside <p> and </p> so that the real output will be something like this:

<p><img src="http://www.gravatar.com/avatar.php?gravatar_id=8f7c605fc5976d190d9b75b43849a18e&rating=R&size=40" alt="" /></p>

Let’s have some modification. What we want to have is that when Gravatar plugin is not working properly or not yet installed, your theme will still work properly. So, we need to set a basic rule here:

  • Identify whether the plugin function is available or not.
  • If the function is available, display the avatar.

If we take a look at the example above, the plugin function is gravatar();. You can identify function existence using this code: <?php if(function_exists('gravatar')) ?>, the whole new theme tag will be like this:

<?php if (function_exists('gravatar')) { ?>
<img src="<?php gravatar("R", 40, "http://path/to/gravatar_default.png"); ?>" alt="" />
<?php } ?>

So, if you release a WordPress theme, you can write:

“This plugin will handle Gravatar plugin if available.”

rather than

This plugin support Gravatar plugin, if you do not want to display Gravatar, open your comments.php file, and remove this line: <p>
<img src=”<?php gravatar(“R”, 40, “http://path/to/gravatar_default.png”); ?>” alt=”” /></p>

It is only an example, you can use the same method (taking advantage of if (function_exists(''))) for or other use.