Home > OS >  Wordpress how to apply specific CSS property based on user role on every page
Wordpress how to apply specific CSS property based on user role on every page

Time:11-24

I am using the theme "Neve".

I have added a custom function to my child's theme > functions.php

Based on the user role, if the user is X role the topbar which appears above the head/nav menu will change colour.

Can someone advise where I may have gone wrong / as to why this is not changing colour when expected to do so?

Kind Regards,

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;
            
    }   
}

Top bar is the red strip where you see the phone icon:

enter image description here

CodePudding user response:

"I need this to apply to all pages without having to use shortcode"

You could use the wp_head action hook to run the following code for every single page without using a shortcode.

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
    }
}

Code goes into the functions.php file of your active theme or child theme.

  • Related