1

I have a plugin in which I need to use the get_editable_roles() function but I keep getting a fatal error saying that the function does not exist.

In my main plugin file I have this code:

function prefix_run_plugin() {
    $plugin = new Plugin_Class("1.0");
    $plugin->run();
    register_activation_hook( __FILE__, array($plugin, 'initialize') );
    register_uninstall_hook( __FILE__, array('Plugin_Class', 'rollback') );
}

prefix_run_plugin();

I need to use the get_editable_roles function in the constructor. It appears that when this function is called, the appropriate WordPress files haven't been loaded yet which leads to a fatal error. All the other WordPress functions are working properly. Any advice would be really appreciated.

Thanks in advance.

  • Removed my comment and added an answer since it includes a good best practices example, I think anyway. – Andrew Bartel Oct 28 '14 at 23:31
1

Figured my comment would actually make a better answer, so here we go.

You can hook other methods within the plugin class onto admin_init (for the admin side) within the constructor, like so:

class Plugin_Class {

    public function __construct() {
        add_action( 'admin_init', array( $this, 'some_other_method' ) );
    }

    public function some_other_method() {
        // do something fancy with get_editable_roles()
    }
}

This is generally better practice, along with hooking onto init for front end stuff, rather than directly calling things from the constructor as it allows everything to load up properly first. Also, other developers can remove the hook if they are using your plugin and want to extend/modify it, without having to directly hack the file. Essentially, your constructor is just a big set of init hooks, or a single hook to a separate initialization method.

Also, keep in mind get_editable_roles() is only loaded in admin areas, where is_admin() would evaluate to true. You might think about putting a check for that somewhere in the plugin too before you attempt to use the editable roles function.

  • Thanks for the answer. I hooked the function prefix_run_plugin to init and things started to work correctly. But I think your solution will work correctly as well. – Hasan Akhtar Oct 29 '14 at 6:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.