php - Defining constant in a plugin to use in another plugin

admin2025-01-07  4

I am wondering if this is possible or if there is another, better way, of doing things. Google-foo didn't help.

So, I have two plugins, aa-frontend and aa-site. I need to define a constant or variable in aa-site/plugin.php and use it in aa-frontend/folder/somefile.php.

Tried with:

function site_wp_features(){
    define('AA_PLUGIN_GUTENBERG', false);
}

add_action('plugins_loaded', 'site_wp_features', 0)

But I get:

Warning: Use of undefined constant AA_PLUGIN_GUTENBERG

Any ideas?

I am wondering if this is possible or if there is another, better way, of doing things. Google-foo didn't help.

So, I have two plugins, aa-frontend and aa-site. I need to define a constant or variable in aa-site/plugin.php and use it in aa-frontend/folder/somefile.php.

Tried with:

function site_wp_features(){
    define('AA_PLUGIN_GUTENBERG', false);
}

add_action('plugins_loaded', 'site_wp_features', 0)

But I get:

Warning: Use of undefined constant AA_PLUGIN_GUTENBERG

Any ideas?

Share Improve this question asked Jun 22, 2019 at 8:44 UnlikeCoderUnlikeCoder 11 bronze badge 3
  • 1 Could you elaborate on what you need this constant for, and what problem you're attempting to solve? I get the feeling that a constant in one of the plugins isn't the best option. – Jacob Peattie Commented Jun 22, 2019 at 8:53
  • @JacobPeattie I have a plugin that has some frontend functions that we use on almost all sites: aa-frontend, and that plugin needs to be updateable, and we have a aa-site plugin that has functions for that site only, and would need to enable or disable functions from aa-frontend. I am using that const for that. – UnlikeCoder Commented Jun 22, 2019 at 8:57
  • @JacobPeattie for example: pp-site: AA-FUNCTION = true pp-frontend: if AA-FUNCTION == true REQUIRE_ONCE file.php – UnlikeCoder Commented Jun 22, 2019 at 8:58
Add a comment  | 

2 Answers 2

Reset to default 0

instead of using a constant, define the variable as an option stored in the wp_options table so that it can be accessed from any plugin.

To ensure that the constant is defined before it is accessed, you can use the init action hook instead of plugins_loaded, as init is fired after wp has finished loading but before any headers are sent.

function site_define_constant() {
    define('AA_PLUGIN_GUTENBERG', false);
}
add_action('init', 'site_define_constant');

AA_PLUGIN_GUTENBERG should be defined by the time wp reaches the init hook, and you should no longer encounter the Use of undefined constant warning.

Then, in aa-frontend/folder/somefile.php, you can access the constant like below code

if (defined('AA_PLUGIN_GUTENBERG') && AA_PLUGIN_GUTENBERG) {
    // Constant is defined and set to true
} else {
    // Constant is either not defined or set to false
}
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736252588a57.html

最新回复(0)