WP-CLI – List All User Roles with Specific Capability


I have stumbled upon a use case where a list of user roles must be retrieved given a specific capability.

The following code accomplishes that.

Here is the WP-CLI command to obtain a list of WordPress user roles with the upload_files capability. You can adjust the capability to your desired use:

capability="upload_files"
wp role list --fields=role --format=csv | tail -n +2 | while IFS= read -r role; do
  if wp cap list "$role" | grep -q $capability; then
    echo "$role"
  fi
done

I have also added this within a GitHub Gist over here.