0
0
Wordpressframework~5 mins

User capability checks in Wordpress

Choose your learning style9 modes available
Introduction

User capability checks help you control what different users can do on your WordPress site. This keeps your site safe and organized.

When you want to show or hide parts of your site based on user roles.
When you want to allow only certain users to edit posts or pages.
When you want to prevent unauthorized users from accessing admin features.
When you want to customize user experience depending on their permissions.
Syntax
Wordpress
current_user_can( string $capability ) : bool

This function returns true if the current user has the given capability.

Capabilities are like permissions, for example 'edit_posts' or 'manage_options'.

Examples
Check if the user can edit posts before showing an edit button.
Wordpress
if ( current_user_can( 'edit_posts' ) ) {
    // Show edit button
}
Only users with admin rights can see settings.
Wordpress
if ( current_user_can( 'manage_options' ) ) {
    // Show admin settings
}
Check if user can publish posts before showing publish options.
Wordpress
if ( current_user_can( 'publish_posts' ) ) {
    // Allow publishing
}
Sample Program

This code checks if the current user can edit posts. It prints a message accordingly.

Wordpress
<?php
// Simple example to show message based on user capability
if ( current_user_can( 'edit_posts' ) ) {
    echo 'You can edit posts!';
} else {
    echo 'You cannot edit posts.';
}
?>
OutputSuccess
Important Notes

Always use capability checks to keep your site secure.

Use current_user_can() inside templates or plugins to control access.

Remember that administrators usually have all capabilities by default.

Summary

User capability checks control what users can do on your site.

Use current_user_can() to check permissions before showing features.

This helps keep your site safe and user-friendly.