DevinVinson / WordPress-Plugin-Boilerplate

[WordPress] A foundation for WordPress Plugin Development that aims to provide a clear and consistent guide for building your plugins.
http://wppb.io
7.69k stars 2.27k forks source link

Conditionally add action in define_admin_hooks() #568

Closed andrewl64 closed 3 years ago

andrewl64 commented 3 years ago

I have the following function defined in admin/class-plugin-name-admin.php :

public function someFunc() {
    // do something
}

And I have the following inside define_admin_hooks():

$this->loader->add_action( 'someHook', $plugin_admin, 'someFunc' );

What I would like to do is conditionally add the above add_action based on a checkbox setting that I have registered for the plugin.

What I have currently done is add the condition within the someFunc() function itself in admin/class-plugin-name-admin.php like this:

public function someFunc() {
    if ( '1' == get_option( 'someCheckbox' ) ) {
        // do something
    }
}

How would I add the condition in the define_admin_hooks() function to not even load the action in the first place if the condition is not met? Something like this:

if (  "the checkbox is checked"  ) {
    $this->loader->add_action( 'someHook', $plugin_admin, 'someFunc' );
}
espiat commented 3 years ago

whats the solution?

andrewl64 commented 3 years ago

whats the solution?

I ended up leaving the if statement within the someFunc() function. Still new to this boilerplate so I'll go through the code again once I'm done with the test plugin I'm building and see if there's a way I can use the above condition in the define_admin_hooks() directly.