【问题标题】:Wordpress: Change user role conditionallyWordpress:有条件地更改用户角色
【发布时间】:2012-02-29 04:29:12
【问题描述】:

我正在为多位作者创建一个 Wordpress 网站,并希望根据文章提交设置用户角色。表示如果任何用户有 0-10 篇文章,他们将转为贡献者角色,如果 11-30 将转为作者角色,如果 31-100 将转为编辑角色。

我还想制作默认注册组为订阅者的注册系统。他们将获得一个链接到验证电子邮件,如

如果您想成为贡献者,请点击以下链接。 (要提交文章,您必须至少具有贡献者权限) http:// 链接将在此处...此链接会自动将用户角色从订阅者更改为贡献者。

希望我能从您的专家那里得到解决方案。寄希望于各位朋友,我发布这个问题。

【问题讨论】:

    标签: wordpress conditional role


    【解决方案1】:

    您想要做的是当他们发布提交检查以查看他们创作了多少帖子然后更改角色。所以在你的主题的functions.php文件中你需要一个像这样的钩子。

    add_action('publish_post', 'update_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 .......
    
    }
    

    【讨论】:

    • 非常感谢您的代码...只是一个简单的问题...它会永久更改用户角色还是只会在发布时检查而不是返回给贡献者?事实上,我会尝试实际看看,但只是问你是否知道..
    • 这将永久改变它。如果你想把它改回来,你需要找出这些条件才能把它改回来。
    • 我想把它改成永久的,所以这正是我要找的。感谢 thenetimp 的帮助,我将尝试此代码并回复您。
    • 我做了一个快速的改变。删除了!在有条件的情况下,您可能想稍微玩一下该逻辑,但基本思想就在那里,此代码不是 100% 您需要围绕您需要的内容进行修改,但这是从 imo
    • 这一行出现语法错误if($numPost &gt; 0 &amp;&amp; $numposts is &lt;= 10 &amp;&amp; current_user_can('subscriber'))
    【解决方案2】:

    使用 SQL 语句(Database Queries)获取 Wordpress 数据不符合 Wordpress 编码标准。 See Wordpress Handbook

    最好使用count_user_posts函数

    See Function on the codex

    【讨论】:

      猜你喜欢
      • 2013-09-17
      • 1970-01-01
      • 2021-07-11
      • 1970-01-01
      • 2016-04-21
      • 2012-06-10
      • 2015-11-11
      • 2020-06-26
      • 2012-06-30
      相关资源
      最近更新 更多