Home » Php » php – WordPress: Check if plugin is installed (ACF)

php – WordPress: Check if plugin is installed (ACF)

Posted by: admin July 12, 2020 Leave a comment

Questions:

I want to prevent fatal error in my theme if the ACF plugin is deactivated or not installed.

The main function of the plugin is get_field().
I wrote this code in my functions.php to check:

if ( !function_exists('get_field') ) {
  function get_field() {
    echo '<span>plugin ACF is not installed</span>';
  }
}

Please tell me this is acceptable practice?

How to&Answers:

First of all, this is not the main plugin function, just one of them. Probably, most commonly used by a plugin user in a theme. Another one is the_field(), which actually prints value (get_field() returns it).

Regarding practice of defining your custom function – it’s fine. However, I would not print that long message in every place where ACF field is expected – some of them may be short (numbers), and this message will break the layout. Printing something shorter is better, imo.

Also, function_exists is proper check, not is_plugin_active, because ACF can also be shipped as a library with a theme framework or other plugin.

Another option is to remove ACF dependency on the frontend completely. You can output the contents of the fields with get_post_meta() and prevent ACF plugin from loading on the frontend entirely. See these two posts for details:

http://www.billerickson.net/code/disable-acf-frontend/

http://www.billerickson.net/advanced-custom-fields-frontend-dependency/

Answer:

ACF itself uses a check to see if the framework has been loaded. If it has already been included and invoked by another plugin or theme, then ACF won’t re-instantiate its own class again. It does this with a class check:

if (!class_exists('ACF')) {
    //  The ACF class doesn't exist, so you can probably redefine your functions here
}

I use exactly this in my own plugins that rely on the presence of ACF so that if it happens to get deactivated, the whole site doesn’t bomb out.

Answer:

Yes, it’s a good way to check if the plugin function exists.

You can also try is_plugin_active function to check if the plugin is activated, because the function can be redeclared somewhere.

I think the main reason you are doing that is to prevent Fatal Errors, so it doesn’t matter which way you can use.