liam
Home // WordPress page access security using current_user_can

WordPress page access security using current_user_can

Posted on

The current_user_can() is another useful function used to check if the current user has a specific capability when visiting a page on your site.

if ( current_user_can( 'administrator' ) || current_user_can( 'director' ) ) {
    // Code here to execute if the current user is an administrator or director
} else {
    // Code to execute if the current user is not an administrator or director
}

By using current_user_can(), you can control access to specific parts of your site based on the user’s role or capabilities.

The following code below will add a new user role called director to your site.

function director_role() {
    add_role( 'director', __( 'Director', 'your-theme-name' ), array(
        'read' => true,
        'edit_posts' => true,
        'delete_posts' => true,
        'publish_posts' => true,
    ) );
}

add_action( 'init', 'director_role' );

You can use is_user_logged_in() to check if a user is logged in before using current_user_can()

if ( is_user_logged_in() && current_user_can( 'administrator' ) ) {
    // Code to execute if the user is logged in and has the 'administrator' capability
} else {
    // Code to execute if the user is not logged in or doesn't have the 'administrator' capability
}

In this example, the code will only execute if both conditions are met:

  1. The user is logged in.
  2. The user has the ‘administrator’ capability.

If either condition is not met, the code within the else block will be executed.

This approach ensures that you’re not checking capabilities for unauthenticated users, which could lead to security risks.

liam