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?
If you know of a class or function that is included with the plugin you're checking for, you can easily use the function_exists() and/or class_exists() functions to determine if the plugin is active. If the function or the class is registered, meaning the plugin is active, the checks will return true.
If you want to show the fields inside the post, you have to place the code inside the loop of "single. php", supposing you are using the standard post type. This code retrive the field only, it won't show anything, it's used to store the value in a variable: get_field('field-name');
To activate your ACF PRO license, you need to paste your license key into the available space on the page at Custom Fields > Updates. Then click the 'Activate License' button. You can find this key on your store account page.
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/
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.
There is a wordpress function for that:
is_plugin_active('advanced-custom-fields/acf.php');
Note: You might run into issues when changing to the premium version of a plugins.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With