The Correct Way To Add Plugin’s Functions Into Themes

I recently deactivated a plugin on this blog only to find that the blog stopped working. Only an error was displayed. The error told me that I was trying to call some function that didn’t exist. So the clear clue was that the function disappeared because of the deactivation of plugin. To check my theory, I re-activated the plugin and the blog started working again.

The plugin I deactivated was related post plugin, and when I checked the theme files, there was a call to the function,

<?php related_posts(); ?>

I removed that function call and deactivated the plugin, which fixed the issue. But I wondered why did the theme author didn’t call the function in the right way.

The Correct Way To Add Plugin’s Functions Into Themes

The correct way to call plugin’s function in a theme is this,

<?php if(function_exists('function_name'))
{
function_name();
}
?>

As you can see in the code snippet above, an if condition is used to check if a function exists. If it doesn’t, then the won’t be called, thus preventing the blog from breaking completely.

So, to call related_posts function, the theme’s author should have added this to theme theme files,

<?php if(function_exists('related_posts'))
{
related_posts();
}
?>

Now, even if the end user deactivates the related posts plugin in future, it won’t affect the blog at all.

If you are a WordPress theme developer and you want to integrate a plugin with a theme, or if you are a WordPress user who need to add a function call to theme files to use some plugin, then please add the function call in the correct way. This will prevent your blog from breaking if you accidentally deactivate the plugin in future.

share on twitter

Leave a Reply