Wordpress: Conditionally role change basis on post

2019-08-18 17:53发布

Since almost 4-5 months I am trying to solve this issue where user role automatic change with certain number of post count. Say if x user have <= 10 post he/she is in contributor role if <=20 author role so on..

With help of you all people I could achieve this code.

<?php

add_action( 'save_post', 'update_roles' );
    function update_roles( $post_id ) {

        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
            return $post_id;

        // Get the author
        $author = wp_get_current_user();

        // Set variables for current user information
        $count = count_user_posts( $author->ID );
        $current_role = (array) get_user_meta( $author->ID, 'wp_capabilities' );

        get_currentuserinfo(); 
        global $user_level;

        // Do the checks to see if they have the roles and if not update them.
        if ( ($user_level != 10) && ( $count > 3 && $count <= 5 ) && ( array_key_exists( 'contributor', $current_role[0] ) ) ) {
            $user_id_role = new WP_User( $author->ID );
            $user_id_role->set_role( 'author' );

        } elseif ( ($user_level != 10) && ( $count > 5 && $count <= 9 ) && ( array_key_exists( 'author', $current_role[0] ) ) ) {

            $user_id_role = new WP_User( $author->ID );
            $user_id_role->set_role( 'editor' );

        } elseif ($user_level != 10){

            $user_id_role = new WP_User( $author->ID );
            $user_id_role->set_role( 'contributor' );

        } return $post_id;

    }

?>

This code working some time and some time doesnt reacting at all. This code is buggy and if once somehow will auto change the role and if I change role again back to down side than it will never auto change as per post count. same if I delete post than its not affecting at all. However it should always consider the post count and imminently should effect with the number of post.

I am really getting tired with this but my entire site is based on this code only. So I really need you great people help.

Thanks a lot lot lot..

1条回答
Lonely孤独者°
2楼-- · 2019-08-18 18:21

what i think is there is a mistake in starting users role because:

if ( ($user_level != 10) && ( $count > 3 && $count <= 5 ) && ( array_key_exists(     'contributor', $current_role[0] ) ) ) {
        $user_id_role = new WP_User( $author->ID );
        $user_id_role->set_role( 'author' );

If user level is 10 AND post count is major than 3 AND minor or equal than 5 set user role to Author

but in the second

} elseif ( ($user_level != 10) && ( $count > 5 && $count <= 9 ) && ( array_key_exists( 'author', $current_role[0] ) ) ) {

        $user_id_role = new WP_User( $author->ID );
        $user_id_role->set_role( 'editor' );

You say again that conditional tag starts only IF THE USER ROLE IS 10... so, for example, if users have posted 4 posts, and it's role is author the conditional tag will not works

查看更多
登录 后发表回答