在用户登录时更改CSS

时间:2015-03-19 作者:Steve Kim

所以我有以下代码:

        <h3>
             <div class="sellertitle"><a class="allseller" href="#">Something</a> </div>

             <?php if ( is_user_logged_in() ) { ?>          
                     <div class="otherseller">  <a class="allotherseller" href="#">Else</a> </div>
             <?php } ?>
        </h3>
然后,对于“sellertitle”,我有以下CSS:

<--logged in-->
.sellertitle {
  float: left;
  width: 49%;      
}
如您所见,“Something”始终可见,“Else”仅在用户登录时可见。

但是,当用户注销时,我希望“sellertitle”CSS为“float:none”

<--logged out-->
  .sellertitle {
   float: none;
   width: 49%;      
 }
实现这一目标的最佳方式是什么?

2 个回复
最合适的回答,由SO网友:Rafael 整理而成

这里是另一种只使用CSS的方法,没有任何内联PHP和不必要的CSS垃圾邮件。如果主题正确使用body_class() 当用户登录时,Wordpress会在body元素中添加一个类“logged in”,因此我们可以在样式表中使用它:

<--logged out-->
.sellertitle {
  float: none;
  width: 49%;      
}

.otherseller {
  display: none;
}

<--logged in-->
.logged-in .sellertitle {
  float: left;     
}

.logged-in .otherseller {
  display: inline;
}

SO网友:Reigel

你可以试试这样的。。。这将在头部添加css

add_action(\'wp_head\', \'add_css_head\');
function add_css_head() {
   if ( is_user_logged_in() ) {
   ?>
      <style>
          .sellertitle {
             float: left;
             width: 49%;      
           }
      </style>
   <?php
   } else {
   ?>
      <style>
          .sellertitle {
             float: none;
             width: 49%;      
           }
      </style>
   <?php
   }
}
另一个是在登录时更改类。。。

因此,您将有两个css

.sellertitle {
  float: none;
  width: 49%;      
}
.sellertitle.logged {
  float: left;      
}
然后在你的div上,像这样的。。。

<div class="sellertitle <?php if ( is_user_logged_in() ) {echo \'logged\';}">

结束