Create two users and compare their capabilities

Description: Create a user meera with the role editor and a user karan with the role subscriber. Print for both users if they can edit_others_posts and publish_posts.

Hint:

  • Use wp user create with --role.
  • The PHP function user_can( $user_id, $capability ) checks a capability.

Solution

Terminal output

$ wp user create meera meera@example.com –role=editor –user_pass=Pass#1234 –porcelain
2
$ wp user create karan karan@example.com –role=subscriber –user_pass=Pass#1234 –porcelain
3
$ wp user list –fields=ID,user_login,roles
ID user_login roles
1 admin administrator
3 karan subscriber
2 meera editor
$ wp eval 'foreach ( array( 2 => "meera", 3 => "karan" ) as $id => $name ) { foreach ( array( "edit_others_posts", "publish_posts" ) as $cap ) { echo $name, " ", $cap, ": ", user_can( $id, $cap ) ? "yes" : "no", "\n"; } }'
meera edit_others_posts: yes
meera publish_posts: yes
karan edit_others_posts: no
karan publish_posts: no

How it works

  • The role gives a set of capabilities. An editor can publish and edit the posts of other users, and a subscriber can do neither.
  • user_can() checks any user by ID, while current_user_can() checks the user who is logged in.

Read Users and Roles.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.