ワードプレスで現在ログインしているユーザーの権限で出来ることを調べるためのPHPコードや何を調べることができるのか等を解説いたします。


現在ユーザーがログインしていて、そのユーザーに投稿の編集権限があるかを調べるPHPコード

このコードは下記のようになります。
テーマのfunctions.phpやプラグインに記載いただくと動作します。

function what_currentuser_can() {
    if ( is_user_logged_in() ) {
        if ( current_user_can( 'edit_posts' ) ){
            //このユーザーは投稿の編集権限があります! ↓この下に処理を記載
        }
    }
}
add_action( 'init', 'what_currentuser_can' );

まず、ユーザーがログイン後に動作するinitアクションで処理に割り込みます。
この時にis_user_logged_in()でユーザーがログイン状態である場合のみ処理を続行し、current_user_can( ‘edit_posts’ ) で投稿の編集権限があるかどうかを調べます。

current_user_can関数はワードプレスの組み込み関数で、current_user_can(調べたいユーザー権限) で現在のユーザーの権限を調べることが可能です。

current_user_can関数で調べることができるユーザーの権限一覧

current_user_can関数で調べることができるユーザーの権限でよく使用されるものは下記のようなものがございます。

ユーザーの権限の種別

current_user_can関数でユーザーの権限の種別を調べることが可能です。

current_user_can( ‘administrator’ ) 管理者権限です
current_user_can( ‘editor’ ) 編集者権限です
current_user_can( ‘author’ ) 投稿者権限です
current_user_can( ‘contributor’ ) 寄稿者権限です
current_user_can( ‘subscriber’ ) 購読者権限です

個別の処理の実行が可能かを調べる

投稿の編集や削除など個別の管理者系の操作を実行できるかどうかも調べることができます。

current_user_can( ‘switch_themes’ )  テーマの切り替えができるか
current_user_can( ‘activate_plugins’ )  プラグインを有効化できるか
current_user_can( ‘install_plugins’ )  プラグインを追加できるか
current_user_can( ‘edit_users’ )  ユーザーを追加編集できるか
current_user_can( ‘manage_options’ )  サイトの設定を変更できるか
current_user_can( ‘manage_categories’ )  カテゴリーを追加できるか
current_user_can( ‘upload_files’ )  ファイルをアップロードして追加できるか
current_user_can( ‘edit_posts’ )  投稿を編集できるか
current_user_can( ‘edit_others_posts’ )  ほかのユーザーの投稿を編集出来るか
current_user_can( ‘publish_posts’ )  投稿を公開できるか
current_user_can( ‘edit_pages’ )  固定ページを編集出来るか
current_user_can( ‘edit_others_pages’ ) ほかのユーザーの固定ページを編集出来るか
current_user_can( ‘delete_pages’ )  固定ページを削除できるか
current_user_can( ‘delete_users’ )  ユーザーを削除できるか
current_user_can( ‘create_users’ )  ユーザーを作成できるか
current_user_can( ‘edit_comment’ ) コメントを編集できるか
current_user_can( ‘create_sites’ ) マルチサイトの子サイトを作成できるか
current_user_can( ‘manage_sites’ ) マルチサイトの子サイトを編集できるか

そのほかにも多数の権限がございます。
こちらよりすべての権限を閲覧いただくことが可能です。
https://wordpress.org/support/article/roles-and-capabilities/

WordPress ワードプレスのテーマやプラグインの修正・カスタマイズのご依頼ご相談はワードプレスドクターまでお気軽にお送りください