WordPress plugin functions: check if function exists

I’m developing a WordPress site that relies on a plugin to be activated for the site to function properly.

The plugin has a few useful functions that I’m using in the site’s template files. When the plugin is active, everything works perfectly. If the plugin is deactivated, the content doesn’t load.

Read More

Wrapping these functions in if(function_exists(...) obviously fixes that, but I’m wondering if there’s a cleaner way of doing that in WordPress. Is there a function that can be placed in the theme’s functions.php file that can check if these functions are available every time I call them, and if not provide a safe fallback without me having to wrap them in the function_exists()?

Thanks.

Related posts

Leave a Reply

3 comments

  1. If you’re only using it sparingly (1-2 times), use if( function_exists() ). If you’re calling the function several times through in different template files, I’d suggest using something like

    In your functions.php

    function mytheme_related_posts( $someparams = nil ) {
      if( function_exists( 'related_posts' ) ) {
        related_posts( $someparams );
      } else {
        echo 'Please enable related posts plugin';
      }
    }
    

    Then use mytheme_related_posts() in your template.

  2. I think this is the most clear way. It prevents all problems. I think you can write a function instead which can check if these functions are available every time you call them, but I’m almost sure it can cause you more trouble and it burns more memory then simply using if(function_exist()). Don’t forget the else branch and it will work fine.