Wordpress: Change user role conditionally

送分小仙女□ 提交于 2019-11-28 01:54:57

问题


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.


回答1:


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 .......

}



回答2:


Using SQL statements (Database Queries) to get at Wordpress data is not in accordance with Wordpress coding standards . See Wordpress Handbook

It would be better to use count_user_posts function

See Function on the codex



来源:https://stackoverflow.com/questions/9181440/wordpress-change-user-role-conditionally

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!