📜  wordpress if admin - PHP (1)

📅  最后修改于: 2023-12-03 15:06:00.209000             🧑  作者: Mango

WordPress If Admin

Introduction

As a programmer working with WordPress, you may need to display or hide certain elements on your website based on the user role or permission level. One of the most common conditions is to check if the user has the administrator role. The WordPress If Admin function can be used to check if the current user is an administrator and perform certain actions accordingly.

Syntax
if(current_user_can('administrator')){
  //code to execute for administrators
}
Explanation

The above code checks if the current user has the administrator role. If they do, then the code inside the curly braces will be executed. This code block can be used to display or hide content, set options, or perform other tasks that should only be available to administrators.

Example

Suppose you have a custom post type that is only editable by administrators. You can use the WordPress If Admin function to restrict access to this post type to only administrator users.

add_action( 'admin_init', 'my_custom_post_type_restrictions' );

function my_custom_post_type_restrictions(){
    $post_type = 'my_custom_post_type';

    if(current_user_can('administrator')) return;

    remove_menu_page($post_type);
    remove_submenu_page($post_type, 'edit.php?post_type='.$post_type);
    remove_submenu_page($post_type, 'post-new.php?post_type='.$post_type);
    remove_submenu_page($post_type, 'edit-tags.php?taxonomy=my_taxonomy&post_type='.$post_type);
}

In this example, the remove_menu_page() and remove_submenu_page() functions are used to remove the menu and submenu entries for the custom post type for non-administrator users.

Conclusion

Overall, the WordPress If Admin function is a powerful tool for developers to check if the current user has the administrator role and perform actions accordingly. By utilizing this function, you can ensure that your website is secure and that sensitive content is only accessible to authorized users.