My application needs to run some scripts, and I must be sure that the user running them is an administrator... What is the best way of doing this using C#?
First off, we check that the user is actually logged in. If they're not logged in, they won't have a role assigned. If the user is logged in, we use wp_get_current_user to return the WP_User object. This provides us with a stack of information about the data and we can access their user role(s) via $user->roles .
Check if Current User is Administrator in WordPress If you want to add functionality only for logged in admins this can be done with the current_user_can() function. By using current_user_can('administrator') in an if statement it'll allow you to check if the current user is a site admin.
You can use the get_current_user_id() method throughout the site. It will return the current users ID if they are logged in, or it will return 0 if the current user is not logged in. @FlemmingLemche WordPress will automatically include your functions.
using System.Security.Principal; public static bool IsAdministrator() { using (WindowsIdentity identity = WindowsIdentity.GetCurrent()) { WindowsPrincipal principal = new WindowsPrincipal(identity); return principal.IsInRole(WindowsBuiltInRole.Administrator); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With