When using WordPress, it’s one thing to set the WordPress user role using the provided interface. And this is what we do if we’re working as administrators of a particular site.

But say you’re working on a project, you need to import users and, as part of the process, set the WordPress user role in the context of the import process.

This could come as importing a new user, or it could come as updating an existing user. It doesn’t matter so much as there is a need to set a user role with working with a user.

The WordPress API makes this pretty easy, but there are two things to understand that, if missed, can result in basically overloading the user with multiple roles.

Here’s what I mean.

The WordPress User Role

First, I’m making the assumption that you’re familiar with WordPress user roles and capabilities. If not, The Codex breaks this down into an easy to understand format.

WordPress User Role: How Capabilities and Roles Work

The capabilities of each role.

Secondly, I’m making the assumption you have some experience working with the WordPress User API. But here’s the use case:

The task is the create a new user (versus update an existing user) and set their role rather than update their role (because users are given a default role of “subscriber.”).

Here’s how to programmatically set the WordPress user role:

It seems straightforward, right? A few things, regarding the code:

  • Notice that this is a public function, so it’s ideally used in the context of a class, but if you wanted to use this procedurally, you’d just drop the word.
  • Secondly, for those who don’t use namespaces, the slash preceding WP_User is telling PHP to use the global namespace so that I have access to the class in WordPress.

And here’s the catch:

There’s a similar function called add_role that might appear to be the proper function to use. But it’s not. Instead, this will add another role to the existing user.

So say a user starts off with the “subscriber” role and then you call add_role on that user and set “editor” for the role, then the user will have both “subscriber” and “editor” as its roles.

But when you opt to use set_role, you’re changing the role from what the user had to a new role. And, often, that’s what you’re after.