Load a different stylesheet in WordPress if an admin is logged in

I want to be able to put a conditional PHP code in my theme which loads a different stylesheet when an admin or just one user (ID=1) is logged in.

Is there a WordPress function to achieve this?

Read More

There’s this div with a class (let’s say “example”) which is set to “display: none” on a post.

I just want admins to view it when they’re logged in and I’ll create a new CSS property for the class like:

.example {
display: block;
}

Related posts

Leave a Reply

5 comments

  1. You can add a function for this in functions.php

    function admin_stylesheet()
    {
        if (current_user_can( 'manage_options' )) {
    
            wp_register_style('admin_css', get_template_directory_uri() . '/admin.css', array(), '1.0', 'all');
            wp_enqueue_style('admin_css'); 
    
        }
    }
    
    add_action('wp_enqueue_scripts', 'admin_stylesheet');
    
  2. I never used WP but if you can edit the code you could do a simple query if the admin is logged in and then use some inline-code

    <div class="example" <?php if($admin == 1){ echo 'style="display: block;"';} else{ echo 'style="display: none;"'; ?>> CONTENT </div>
    
  3. I would do three things:

    1) Make sure you use the standard WordPress body_class function in your template. This will add lots of helpful classes to the body element of your HTML.

    2) Add a filter on body_class to add a new helper class to the body when the user is an admin user. For example, in your theme’s functions.php:

    // Add specific CSS class by filter
    add_filter('body_class','my_class_names');
    function my_class_names($classes) {
        if (is_user_logged_in() && current_user_can('manage_options')) {
            $classes[] = 'admin-user';
        }
        return $classes;
    }
    

    3) Use this new class in your standard CSS stylesheet to override your default when on an admin page:

    .admin-user .example {
        display: block;
    }
    

    This solution does things in a pretty standard, theme-friendly way, and avoids using either a separate stylesheet or an inline style.

  4. You can write like as follows

    <?php 
         if ( is_user_logged_in() && current_user_can( 'manage_options' ) ) {
            ?>
            <style>
                   .example {
                        display: block;
                    }
            </style>
            <?php 
         } 
    ?>