Skip to main content

User

User class represents a WordPress user in WP-Node. It is a transient component that resolves the user by ID, username, or email, and provides access to user roles and capabilities. It supports permission checks and anonymous fallback.


Description​

This class is responsible for:

  • User Resolution: Resolves user from ID, username, or email using userRef.
  • Role Assignment: Fetches roles from user meta (_capabilities) and adds superadmin for multisite.
  • Capability Checks: Supports both single (can) and bulk (bulkCan) capability checks.
  • Anonymous Handling: Automatically assigns an anonymous identity when no user is found.

Properties​

  • meta: Meta
    Handles user-specific metadata operations.

  • props: types.Tables["users"] | undefined
    Contains the WordPress user object. Returns undefined if the user is anonymous or invalid.


Methods​

hasCapabilities(capabilities: string[], options?: { blogIds: number[] }): Promise<boolean>​

Checks if the user has any of the given capabilities.
Uses UserUtil internally.


role(): Promise<Role>​

Returns the user's primary role after resolving roles.


roles(): Promise<string[]>​

Resolves all roles assigned to the user:

  • Reads from user meta key _capabilities.
  • Adds superadmin if found in site_admins.
  • Merges capabilities into a single Role instance.

can(action: string, ...args: any[]): Promise<boolean>​

Checks if the user can perform a given action.
Returns true or false.


bulkCan(...)​

Runs multiple capability checks in batch.
Accepts:

  • A single action and list of arguments.
  • An array of [action, ...args] tuples.

Returns an array of [action, args, result] values.


init(): Promise<this | void>​

Resolves the user using userRef and populates props and meta.
Automatically triggered via @asyncInit.


Usage​

const context = await Application.getContext();
await context.current.assumeUser(1);

const user = context.current.user!;

await user.can("edit_post", postId);

const results = await user.bulkCan([
["edit_post", postId],
["edit_comment", commentId],
["edit_posts"],
]);