Limit page creations by user role functions.php

80 Views Asked by At

Is it possible to create a function via functions.php that restricts users from creating pages based on their user role? So for example, users with the user role "limited" can only create 5 pages.

When they reach this amount, the "Create new page" button must be gone or they have te receive a message that they reached there limit and have to contact there admin.

I know there is a plugin called Bainternet Posts Creation Limits but this is causing some problems.

Is something possible with a function?

EDIT:

Ok, I tried the code below but aint working and to be honest my coding skills are to poor to make something of it.

Anybody else any ideas?

1

There are 1 best solutions below

3
Ruben Pauwels On

You could try something like this:

Step 1: Upon user creation: give your user the capability 'publish_pages'

Step 2: Save in the user_meta how many pages the user has created.

Step 3: If the user has 5 or more pages remove the capability from this user.

STEP 1 & 2 (untested):

add_action( 'user_register', 'user_registered', 10, 1 );

function user_registered( $user_id ) {

    // ADD CAPABILITY
    $user = new WP_User( $user_id );
    if ( ! empty( $user->roles ) && is_array( $user->roles ) && in_array( 'YOURROLEHERE', $user->roles ) ) {
        $user->add_cap( 'publish_pages');
        update_user_meta($user_id, 'numberofpages', 0);
    }     

}

STEP 3 (untested):

add_action('publish_page', 'user_published_page');

function user_published_page(){
    // GET CURRENT USER
    $user_id = get_current_user_id();
    $user = new WP_User( $user_id );

    // CHECK ROLE
    if ( ! empty( $user->roles ) && is_array( $user->roles ) && in_array( 'YOURROLEHERE', $user->roles ) ) {
       // GET NUMBER OF PAGES CREATED
       $numberofpages = intval(get_user_meta($user_id, 'numberofpages', true));

        if($numberofpages >= 5){
            $user->remove_cap( 'publish_pages');
        } else {
            update_user_meta($user_id, 'numberofpages', $numberofpages + 1);
        }
    }
}