I have below function on my plugin which adds more capabilities to current user.

// Role setting for add media
function wh_edit_roles(){
    if ( current_user_can( 'edit_posts' ) ){
        $user = new WP_User(get_current_user_id());
add_action('wp_head', 'wh_edit_roles');

According to WordPress's add_cap codex, it is recommended to run this function on plugin activation. What is the proper way to run this function on plugin activation instead of wp_head hook?

Thank you!


That depends on whether your plugin is written in a procedural or object oriented style.

register_activation_hook is what you want. https://codex.wordpress.org/Function_Reference/register_activation_hook

How exactly you incorporate it depends on your plugin coding style. Examples listed in the Codex show multiple approaches.

Procedural example: If you have a function called myplugin_activate() in the main plugin file at either: wp-content/plugins/myplugin.php or wp-content/plugins/myplugin/myplugin.php

use this code:

function myplugin_activate() {

    // Activation code here...
register_activation_hook( __FILE__, 'myplugin_activate' );

f your plugin uses the singleton class pattern, add the activation hook like so:

class MyPlugin {
     static function install() {
            // do not generate any output here
register_activation_hook( __FILE__, array( 'MyPlugin', 'install' ) );

Don't forget to include a companion deactivation hook, especially if you are setting cron jobs and performing other tasks that need clean-up if the plugin is deactivated or deleted.

| improve this answer | |

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.