Puddinq.com sharing knowledge
';

WordPress add user capability on plugin activation

WordPress add user capability on plugin activation

In the situation below is a class with two methods which could be hooked to plugin (de)activation. The first gets the user with the same e-mail address as the website (settings->general) and adds a capability to that user. The second removes the capability from all users that have it.

class nfDashActivator
{
    static function activate() {

        // give admin capability to controll all
        $admin_email = get_option('admin_email');
        $admin_user  = get_user_by('email', $admin_email);

        if (isset($admin_user)) {
            $admin_user->add_cap('nf_dash_control');
        }


    }

    static function deactivate() {

        global $wpdb;

        // remove capability

        // meta-key name
        $capabilities_field_name=$wpdb->prefix.'capabilities';
        //array as argument for our query
        $qargs=[
            'role' => ['Administrator'], // use this if you need to query by role at the same time
            'meta_query'=>
                [
                    //'relation' => 'OR', // optional if you'll need to select more than
                    //  one capability just add this and create same array
                    // as down below describing what are you looking for
                    [
                        'key' => $capabilities_field_name,
                        'value' => 'nf_dash_control', //rolename placed in "" in json it is quoted
                        'compare' => 'LIKE',
                    ],

                    // here could be same array [key,value,compare]... as above with another capability
                    // but you'll need to add extra argument showing relationship between them see above 'relation parameter'

                ]
        ];

        $usersQuery = new \WP_User_Query($qargs); // instantiate UserQuery with $qargs

        $users = $usersQuery->get_results(); // get all results as array of WPUser objects

        foreach ($users as $user) {
            $user->remove_cap( 'nf_dash_control' );
        }

    }
}