【问题标题】:Wordpress how to apply specific CSS property based on user role on every pageWordpress 如何根据每个页面上的用户角色应用特定的 CSS 属性
【发布时间】:2022-01-01 05:28:10
【问题描述】:

我使用的是“Neve”主题。

我给my child's theme > functions.php添加了一个自定义函数

根据用户角色,如果用户是 X 角色,则显示在 head/nav 菜单上方的顶栏将改变颜色。

有人可以告诉我哪里可能出错了/为什么这在预期的时候没有改变颜色?

亲切的问候,

function topbar_switcher () {
    
    $current_user = wp_get_current_user();
    
    switch (true)  {
    case ( user_can( $current_user, "subscriber") ):
        ?>
            <style> 
                .header-top {
                background-color:black;
                }
            </style>
        <?php
    break;
 case ( user_can( $current_user, "customer") ):
        ?>
            <style> 
                .header-top {
                    background-color:#00337f;
                }
            </style>
        <?php
    break;
 case ( user_can( $current_user, "administrator") ):
    ?>
            <style> 
                .header-top {
                    background-color:yellow;
                }
            </style>
        <?php
 break;
            
    }   
}

顶部栏是您看到电话图标的红色条:

【问题讨论】:

  • 您不应该在代码中添加额外的样式。在 CSS 中完成这一切。然后给它一个类名并在代码中使用它。
  • @MarkusZeller 抱歉,我是 wordpress 和自定义功能等方面的新手,抱歉是什么意思? .header-top { 已经存在于我的 CSS 样式表中
  • 添加三个自定义css样式,如.header-top.subscriber { color: green}.header-top.customer{ color: blue}等。然后在您的代码中使用适当的模板文件并使用$color = 'subscriber'; ... &lt;div class="header-top $color"&gt;;
  • 嗨@MarkusZeller 我正在努力为顶栏元素找到合适的模板文件(Neve 是模板)。您能否建议一种替代方法来实现我的需要,谢谢
  • @richag By "出现在 head/nav 菜单上方的顶部栏",你的意思是 wordpress 管理栏吗?

标签: php css wordpress wordpress-theming custom-wordpress-pages


【解决方案1】:

“我需要将其应用于所有页面,而无需使用短代码”

您可以使用 wp_head 操作挂钩为每个页面运行以下代码,而无需使用短代码。

add_action('wp_head', 'changing_color_of_top_navbar');

function changing_color_of_top_navbar()
{

    $current_user = wp_get_current_user();

    $user_roles = $current_user->roles;

    if (in_array("subscriber", $user_roles)) {
        ?>
        <style>
            .header-top {
                background-color: black;
            }
        </style>
    <?php
    } elseif (in_array("customer", $user_roles)) {
    ?>
        <style>
            .header-top {
                background-color: #00337f;
            }
        </style>
    <?php
    } elseif (in_array("administrator", $user_roles)) {
    ?>
        <style>
            .header-top {
                background-color: yellow;
            }
        </style>
    <?php
    }
}

代码进入您的活动主题或子主题的functions.php 文件。

【讨论】:

  • 完美运行,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-25
  • 2018-07-31
  • 1970-01-01
  • 2019-11-02
相关资源
最近更新 更多