[WordPress]Check the activation of plug-ins in PHP and separate the process.

WordPress has a wealth of useful and abundant plugins, which often depend on them when creating a theme.
When you switch themes then, when the plugins that the theme depends on are not activated (and not installed),

「There has been a critical error on your website. Please check your site admin email inbox for instructions.
Learn more about debugging in WordPress.

and a WordPress error may be displayed.

This happens because you are calling a plugin function but the plugin is not activated.
( It’s hard to tell because it’s also displayed with other errors. )

In this case, check the activation in “Smart Custom Fields” and branch the process.

目次

Check plugin activation in functions.php

This is determined by whether the class method used by the plugin exists.

In the case of Smart Custom Fileds, the SCF class method is used. get, click here.

SCF::get

The functions.php determines whether this class method is available.
By putting the ‘object class name’ in the first argument of the method_exists function and the ‘method name’ in the second argument, true is returned if it is defined.

// check activation of plug-ins.
if (method_exists('SCF', 'get')) {
 // When the plug-in was activated.
}

Check plugin activation in page.php

Fixed pages also use method_exists to determine if a class method is available.

The point is that if method_exists does not confirm the existence of the method, it returns.
This prevents subsequent processing.

<?php
/**
 * Template Name: test-template
 *
 */

// check activation of plug-ins.
if (!method_exists('SCF', 'get')) {
    echo 'Smart Custom Fields plugin is not active.';
    return;
}
?>

Summary

When you create a theme that relies on plugins, put guards in place to make sure they don’t fall off.

よかったらシェアしてね!
目次