wordpressconditional-statementsrole

Wordpress: Change user role conditionally


I am creating a Wordpress website for multi author and want to set user role as per article submission. Means if any user have 0-10 article they will go to Contributor role, if 11-30 will go to Author role if 31-100 will go to Editor role.

Also I want to make registration system where default registration group will be Subscriber. They will get a link into verification email like

If you want to become a Contributor please click on below link. (To submit an article you must have at least Contributor permission) http:// link will be here ... this link automatically change user role from Subscriber to Contributor.

Hope I will get solution from you expert. I am posting this issue with lots of hope from you friends.


Solution

  • What you want to do is when they post their submission check to see how many posts they have authored and then change the role. So in your theme's functions.php file you'd need a hook that is like this.

    add_action('publish_post', 'update_roles');
    

    and then a function to update the roles.

    function update_roles()
    {
    
       global $wpdb;
    
       // Get the author
       $author = wp_get_current_user();
    
       // Not sure if $author and $u are the same object I suspect they are. 
       // so this may not be necessary, but I found this code elsewhere.
       // You may be able to do without this and just replace $u with $author later in the code.
       // Get post by author
       $posts = $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE post_author = " . $author->ID );
    
       $numPost = count($posts);
    
       // Do the checks to see if they have the roles and if not update them.
       if($numPost > 0 && $numposts <= 10 && current_user_can('subscriber'))
       {
           // Remove role
           $author->remove_role( 'subscriber' );
    
           // Add role
           $author->add_role( 'contributor' );
    
       }
    
       ...... other conditions .......
    
    }