开发者

Simple PHP Question: Conditional CSS class based on user

I am using this code to show a different styling class for the comment box if the comment is made by the Admin

<li cla开发者_如何转开发ss="<?php if ($comment->user_id == 1) $oddcomment = "authorstyle"; echo $oddcomment; ?>"></li>

The admin has the user_id = 1. Now, what if i want to add user_id 5 and 6, how would I edit this code?


You could either use the || operator (which means or):

if ($comment->user_id == 1 || $comment->user_id == 5 || $comment->user_id == 6)

Or you could use in_array:

if (in_array($comment->user_id, array(1, 5, 6))

Which looks nicer and is more maintainable. :)


One (possibly) robust way to handle this kind of situation is to ask if the userid is one of a set of userids, thus something fairly trivial as a condition is:

in_array($comment->user_id, array(1,5,6))

Clearly you're developing some kind of permission system, so you'd really be better off coming up with a way to abstract user rights from their identities, and verifying a user has some privilege or status rather than in each place checking for said status.

One way to do this might be assigning a user to an admin group, and then checking against the group, rather than against all ids. Better still, you could consider setting some number of properties on the group, say, has_style_xyz, then check against has_style_xyz in your conditional.


You could use something like this:

<li class="<?php
  if ($comment->user_id == 1)
     $oddcomment = "authorstyle";
  if ($comment->user_id == 2)
     $oddcomment = "somethingelse";
  if ($comment->user_id == 3)
     $oddcomment = "blahbalh";
 echo $oddcomment; ?>"></li>

... and so on, for multiple styles.

<li class="<?php
  if ($comment->user_id == 1 || $comment->user_id == 4 || $comment->user_id == 5)
     $oddcomment = "blahbalh";
 echo $oddcomment; ?>"></li>

... for multiple IDs with one style.


Simply use OR or || in your if statement.

<li class="<?php if ($comment->user_id == 1 || $comment->user_id == 5 || $comment->user_id == 6) $oddcomment = "authorstyle"; echo $oddcomment; ?>"></li>


You can try this code

<?php 
if ($comment->user_id == 1) 
   $oddcomment = "authorstyle"; 
else($comment->user_id == 5)
    $oddcomment = "authorstyle2"; 
else($comment->user_id == 6)
    $oddcomment = "authorstyle3"; 
?>

<li class="<?php echo $oddcomment; ?>"></li>


In a simple way you could do something like this:

     <?php
        $liStyles[1] = 'authorstyle';
        $liStyles[5] = 'somestyle';
        $liStyles[6] = 'someotherstyle';
     ?>



 <li class="<?php echo $liStyles[$comment->user_id]; ?>"></li>


I would advise against using the user's ID to determine their admin status because then you will have to manually add/remove each user's ID.

This website is exactly what you want to do.

http://buildinternet.com/2009/09/automatically-highlight-admin-comments-in-wordpress/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜