Skip to content

Latest commit

 

History

History
96 lines (75 loc) · 2.22 KB

File metadata and controls

96 lines (75 loc) · 2.22 KB

Capability Checks - Not Role Names!

The Problem

Checking role names instead of capabilities:

  • Breaks with custom roles - Your check won't work
  • Not flexible - Can't grant capability to other roles
  • Against WordPress philosophy - Capabilities are the API
  • Maintenance nightmare - Must update everywhere for new roles

Bad Practice

// WRONG: Checking role name
if ( in_array( 'administrator', $user->roles ) ) {
    delete_posts();
}

Problems:

  • Doesn't work with custom roles
  • What about shop_manager, editor, custom roles?
  • Must change code to add new roles

Good Practice

// CORRECT: Check capability
if ( current_user_can( 'delete_posts' ) ) {
    delete_posts();
}

Benefits:

  • Works with ANY role that has the capability
  • Add capability to any role via admin
  • WordPress's intended API

Common Mistakes

Mistake 1: is_admin()

// WRONG: Checks if on admin page, NOT user role!
if ( is_admin() ) { }

// RIGHT: Check capability
if ( current_user_can( 'manage_options' ) ) { }

Mistake 2: Role Names

// WRONG
if ( in_array( 'editor', $user->roles ) ) { }

// RIGHT
if ( current_user_can( 'edit_others_posts' ) ) { }

Mistake 3: Not Checking Object-Specific

// WRONG: General capability
if ( current_user_can('edit_posts' ) ) {
    wp_update_post( $post_id ); // Can they edit THIS post?
}

// RIGHT: Object-specific
if ( current_user_can( 'edit_post', $post_id ) ) {
    wp_update_post( $post_id );
}

Key Capabilities

  • manage_options - Site settings
  • edit_posts - Edit own posts
  • edit_others_posts - Edit others' posts
  • publish_posts - Publish posts
  • delete_posts - Delete own posts
  • delete_others_posts - Delete others' posts
  • edit_users - Edit users
  • delete_users - Delete users
  • manage_categories - Manage categories

Key Takeaways

Check capabilities, not roles
Use object-specific checks (edit_post, $post_id)
Check BEFORE every sensitive action
Use current_user_can() consistently
Register custom capabilities properly

❌ Don't check role names
❌ Don't use is_admin() for permissions
❌ Don't skip permission checks
❌ Don't use deprecated user levels