Wordpress: Change user role conditionally

只愿长相守 提交于 2019-11-29 08:21:13

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

}

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

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