【问题标题】:Custom post type count - change user role自定义帖子类型计数 - 更改用户角色
【发布时间】:2017-01-25 07:28:32
【问题描述】:

我一直在尝试找出以下场景的解决方案。我有一个自定义帖子类型 - job_listing 使用 WP Job Manager 插件。

我想要实现的是根据job_listing 帖子计数更改默认用户角色。 所以默认情况下,用户的角色是'subscriber',但是每当用户提交工作列表时,这个用户角色应该会自动更改为'employer'

我在此基础上整理了从各种 tuts 中收集的一段代码。但我仍然无法让这件事发挥作用。

这是我在functions.php中的代码:

add_action ('publish_post', 'update_roles');
function update_roles ($post_type = 'job_listing', $post_status = 'publish') {

   global $wpdb;
   $author = wp_get_current_user();

   $query = "SELECT COUNT(*) FROM $wpdb->posts WHERE post_author = $author->ID AND post_type = '$post_type' AND post_status = '$post_status'"; 
    $count = $wpdb->get_var($query);

   if($count > 0 && current_user_can('subscriber'))
   {
       // Remove role
       $author->remove_role( 'subscriber' );

       // Add role
       $author->add_role( 'employer' );

   }

} 

我做错了什么?

【问题讨论】:

    标签: php wordpress custom-post-type user-roles


    【解决方案1】:

    没有测试,但我从今天早上开始看这个问题,发现没有人回答,所以我想回答它。请试试这个。

    add_action( 'save_post', 'change_author_role', 3 );
    function change_author_role( $post_id ){
        $slug = 'job_listing';
        global $post;
        // If this isn't a 'job_listing' post, don't update it.
        if ( $slug != $post->post_type ) {
            return;
        }
    
        //here check if already a employer or admin 
    
        wp_update_user( array('ID' => get_current_user_id(), array( 'roles' => array( 'Subscriber', 'Administrator' ) ) ) );
    
        //$role = array( 'Subscriber', 'Administrator' );
        //$user = new WP_User(get_current_user_id());
        //$user->set_role($role);
    
    }
    

    【讨论】:

    • 您好,非常感谢您的努力,尝试了您的解决方案,但不,似乎仍然没有做任何事情..
    • @JoeBloggs 我刚刚更新了代码以将作者的 id 提供给wp_update_user 试试这个,否则我们需要更改操作挂钩。
    • 再次感谢。我在这行代码中遇到语法错误:wp_update_user( 'ID' => $_POST['listing_author'], array( 'roles' => array( 'employer' ) ) );,只是无法弄清楚那里可能有什么问题。你能再检查一下吗?
    • @JoeBloggs 我会在我在家时进行调查,现在可能在 3/4 小时后尝试检查 wp_update_user 采用的参数并尝试使其正确或让我知道确切的语法你得到的错误。如果您无法调试,您也可以尝试update_user_meta( $this->ID, $this->cap_key, $this->caps );,我会在家时研究它。
    • 非常感谢,非常感谢您的帮助@PrafullaKumarSahu。我正在使用 Dreamweaver 编辑 php 文件,当我输入您的代码时,我在前面提到的那一行中遇到错误,这意味着它可能只是某个地方的错误或缺失字符,例如 ,; 或和额外或缺少) 类似的东西,真的很小,但我不知道它可能是什么。我是从这里的类似帖子中出来的 [link]stackoverflow.com/questions/10920862/… ,如果有帮助的话。
    猜你喜欢
    • 2021-06-09
    • 2020-12-29
    • 1970-01-01
    • 2012-09-01
    • 2018-03-10
    • 1970-01-01
    • 1970-01-01
    • 2015-04-02
    • 2012-12-14
    相关资源
    最近更新 更多