How to call plugin functions in a custom template

There can be various reason for the undefined function error:

  • The plugin might load its function definitions later than template_include or in the admin backend only.

  • You might have made a syntax error, for example if the plugin is using a namespace, but you are calling the function without that namespace. Or the function is really a class method, and you treat it as a function …

Another question is: Why would you call that function directly? Templates should have as little dependencies as possible. Imagine someone finds a security problem in the plugin, and you have to turn it off. Do you really want to edit all your template files then? Probably not. πŸ™‚

It is much better to keep that dependency out of the template and call a custom action instead. For example, in your template you can replace the direct call with an action call:

do_action( 'frontend.message' );

In your theme’s functions.php, you register a callback for that action:

add_action( 'frontend.message', 'my_frontend_message' );

function my_frontend_message()
{
    if ( ! function_exists( 'plugin_frontend_message' ) ) {

        // Show debug info for those who can do something about it.
        if ( current_user_can( 'manage_option' ) ) {
            print '<p class="error">Function plugin_frontend_message() not found.</p>';
        }
        return;
    }

    print plugin_frontend_message();
}

If you turn off the plugin now, nothing bad will happen, your visitors will just see nothing instead of a message.