How do I write a function to determine if the user is either the node author or admin?
if ( logged user is author || admin ) {
// …
}
It is for the node template.
How do I write a function to determine if the user is either the node author or admin?
if ( logged user is author || admin ) {
// …
}
It is for the node template.
Put this to template.php file of your theme:
function YOUR_THEME_NAME_preprocess_node(&$variables) {
global $user;
if(in_array('administrator', $user->roles) || $variables['node']->uid == $user->uid) {
$variables['is_admin_or_author'] = TRUE;
}
else {
$variables['is_admin_or_author'] = FALSE;
}
}
then in your node.tpl.php or node--your-content-type.tpl.php you'll have a variable $is_admin_or_author with either TRUE or FALSE value.
Instead of checking if the user is the author or admin, it is recommended to check for permissions to perform a certain action. That will make your system more flexible and you're fully taking advantage of the permission system already built into Drupal.
For instance, if you want to show/hide something depending on the permission to edit the current node, you can use this (assuming you're working with node.tpl.php):
function YOUR_THEME_NAME_preprocess_node(&$variables) {
if (node_access('update', $variables['node'])) {
$variables['permission_to_edit'] = TRUE;
}
else {
$variables['permission_to_edit'] = FALSE;
}
}
Now you can use the following in your node.tpl.php:
if ($permission_to_edit) {
print "You may edit this node!";
}
if
-statements because the code would always be if (user_access('get hamburgers')) { }
.
global $user;
if ($node->uid == $user->uid || $user->uid == 1) {
return TRUE;
}
else {
return FALSE;
}
You can also check for user roles by adding in_array('administrator', array_values($user->roles))
to the if statement if you had a seperate role (webmaster for example).