Halloween Sale 15% off Ends in See the plans
PHP

Comment Moderator Role

Adds a "Comment Moderator" role that can approve, edit and delete comments without being able to publish or edit other people's posts.

Don’t have WPIDE yet? Install it on your site

Code

// Role ID and the name shown on the Users screen.
$wpide_cmod_role = 'wpide_comment_moderator';
$wpide_cmod_name = 'Comment Moderator';

$wpide_cmod_add = function ( $roles ) use ( $wpide_cmod_role, $wpide_cmod_name ) {
    if ( ! $roles instanceof WP_Roles || isset( $roles->role_objects[ $wpide_cmod_role ] ) ) {
        return;
    }

    // edit_posts is needed to open the Comments screen; it only allows drafts of their own.
    $caps = array( 'read' => true, 'edit_posts' => true, 'moderate_comments' => true );

    $roles->roles[ $wpide_cmod_role ]        = array( 'name' => $wpide_cmod_name, 'capabilities' => $caps );
    $roles->role_objects[ $wpide_cmod_role ] = new WP_Role( $wpide_cmod_role, $caps );
    $roles->role_names[ $wpide_cmod_role ]   = $wpide_cmod_name;
};

$wpide_cmod_add( wp_roles() );
add_action( 'wp_roles_init', $wpide_cmod_add );

// Moderators may edit any comment, without needing edit rights on the post it belongs to.
add_filter( 'map_meta_cap', function ( $caps, $cap, $user_id ) use ( $wpide_cmod_role ) {
    if ( 'edit_comment' !== $cap ) {
        return $caps;
    }

    $user = get_userdata( $user_id );

    if ( $user && in_array( $wpide_cmod_role, (array) $user->roles, true ) ) {
        return array( 'moderate_comments' );
    }

    return $caps;
}, 10, 3 );

// Keep the Posts and Tools menus out of their way.
add_action( 'admin_menu', function () use ( $wpide_cmod_role ) {
    if ( in_array( $wpide_cmod_role, (array) wp_get_current_user()->roles, true ) ) {
        remove_menu_page( 'edit.php' );
        remove_menu_page( 'tools.php' );
    }
}, 99 );

Notes

The role is registered in memory only; users given this role lose it (and fall back to no role) if the snippet is turned off.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.