I'm going to be using add_role() and $role->add_cap() to set up a new custom role and attach a new capability to existing roles.

I'm wondering where the best place to do this is? Obviously I can do it straight inside functions.php and be done with it. But is this the best practice? Do I only need to do this on admin_init? or should I do it on init?

I'm not entirely sure what the best practices are around using init action hooks rather than just dropping a direct function call inside functions.php.

thanks for your input!

When adding a role and capabilities you only need to run the code once since the roles and capabilities are saved to the database when using add_role or ->add_cap functions so just like Andy said you can use after_setup_theme for this kind of action but add some kind of check so it only runs once, like register_activation_hook or using options:

add_action('after_setup_theme','my_add_role_function');

function my_add_role_function(){
    $roles_set = get_option('my_roles_are_set');
    if(!$roles_set){
        add_role('my_role', 'my_roleUser', array(
            'read' => true, // True allows that capability, False specifically removes it.
            'edit_posts' => true,
            'delete_posts' => true,
            'upload_files' => true 
        ));
        update_option('my_roles_are_set',true);
    }
}

    For plugins, I have had success using plugins_loaded for this. For themes, I would use after_setup_theme.


    'WEB > WP(WordPress)' 카테고리의 다른 글

    Code To Integrate WordPress Media Uploader In Plugin or Theme  (0) 2018.04.10
    How to insert data using wpdb  (0) 2018.04.09
    Using WPDB in standalone script?  (0) 2018.04.08
    Get user role by ID Wordpress  (0) 2018.04.08
    [function] get_post  (0) 2018.04.07

    + Recent posts