Check if a WordPress plugin is active

To manage my blog, I use the Advanced Custom Fields – ACF plugin for custom fields. For this reason, I have created a series of plugins in which I include code to display the data through the ACF.

These codes work perfectly—or so I thought—until it occurred to me to wonder. What would happen if I disabled the Advanced Custom Fields and leave the add-ons, I’ve created active?

To answer that question, I went to my testing website and turned off the ACF. The result was that the blog stopped working. It was an expected result since in these plugins I had incorporated a tag that depends exclusively on the ACF – “get_field”.

The plugins I had created couldn’t stay that way, because if you disabled the Advanced Custom Fields, the website wouldn’t work, so I started looking for the solution to the problem.

I found the solution in Codex WordPress which consists of the following:

  1. Incorporate the is_plugin_active function into the script that makes up the plugin to check if the plugin is active, in my example the Advanced Custom Fields.
if(is_plugin_active('plugin-directory/plugin-file.php')) {
}

Where plugin-directory is the folder where the plugin is, and plugin-file.php is the specific name of the plugin’s file.

In my case:

if(is_plugin_active('advanced-custom-fields/acf.php')) {
}

Where advanced-custom-fields is the name of the folder, and acf.php is the specific name of the plugin file.

  1. In the brackets is the function of the add-in that you had previously created.

It means that we go from this:

function insertautor($content) {
if(get_field('Autor')):
echo '<h2 itemprop="author">', the_field("Autor"),'</h2>';
endif;
return $content;}
add_filter ('the_content', 'insertautor', 1, 1);

To this:

if (is_plugin_active('advanced-custom-fields/acf.php' ) ) {
function insertautor($content) {
if(get_field('Autor')):
echo '<h2 itemprop="author">', the_field("Autor"),'</h2>';
endif;
return $content;}
add_filter ('the_content', 'insertautor', 1, 1);
}

After testing, the modifications worked perfectly. So, if I turn off the ACF, the website doesn’t crash and continues to work normally, although of course, it doesn’t show the information in the custom fields.

Also, if the ACF plugin is active and the custom plugins I’ve created are active, then the information will be displayed. And finally, if the ACF plugin or custom plugins are disabled, the website continues to function normally.

Reference: https://codex.wordpress.org/Function_Reference/is_plugin_active

Califica post

Discover more from Politikaperu

Subscribe to get the latest posts to your email.

Discover more from Politikaperu

Subscribe now to keep reading and get access to the full archive.

Continue reading