current_user_can()
checks for a capability, eg: edit_posts, not a role.
The only capabilities subscribers have is read which only gives them access to the dashboard to change their profile (unless you added additional caps). They can’t even publish a post so you will have to start with contributors.
$old_role = get_user_meta( $user_id, 'wp_capabilities' );
elseif ($numPost > 3 && $numPosts <= 5 && array_key_exists( 'contributor', $old_role ) )
{
$user_id_role = new WP_User($user_id);
$user_id_role->set_role('author');
} elseif ($numPost > 6 && $numPosts <= 9 && array_key_exists( 'author', $old_role ) )
{
$user_id_role = new WP_User($user_id);
$user_id_role->set_role('author');
}
What we are doing is using get_user_meta()
to retrieve the value of wp_capabilities from the usermeta table. Since the value of that field is an array: Array
(
[contributor] => 1
)
and the role is one of the keys we can use the php array_key_exists() function to check if the role exists for that user. Also adding to this that instead of running your custom SQL you can use the count_user_posts()
function to get the post count.
Full Example:
Update: This is fully tested and works.
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' );
// Do the checks to see if they have the roles and if not update them.
if ( ( $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 ( ( $count > 6 && $count <= 9 ) && ( array_key_exists( 'author', $current_role[0] ) ) ) {
$user_id_role = new WP_User( $author->ID );
$user_id_role->set_role( 'editor' );
} return $post_id;
}