body_class hook for admin pages

The body_class hook seem only to work with non-admin pages. When I do

add_filter('body_class', 'add_body_classes');
function add_body_classes($classes) {
        $classes[] = 'myclass';
        return $classes;
}

Is there another hook i should be using if i want to add a class to the body of an admin page?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Admin pages don’t use the body_class filter, use the admin_body_class filter to add classes to admin body tag instead.

Note that $classes in that case is a string, not an array.

Method 2

Mamaduka answer pointed me to the right direction, here is the code for adding classes to the body in the dashboard.

The callback function should return a valid value for the HTML class attribute, that is space separated class names, also, don’t forget to prepend (or append) any existing classes, you should understand by reading the code.

add_filter( 'admin_body_class', 'my_admin_body_class' );

/**
 * Adds one or more classes to the body tag in the dashboard.
 *
 * @link https://wordpress.stackexchange.com/a/154951/17187
 * @param  String $classes Current body classes.
 * @return String          Altered body classes.
 */
function my_admin_body_class( $classes ) {
    return "$classes my_class";
    // Or: return "$classes my_class_1 my_class_2 my_class_3";
}

Method 3

Adding multiple classes, and especially when they must display based on some conditions, may result in an inconsistent HTML output.
To format it correctly and also have the ability to remove duplicates or existing classes, we can convert them to array and in the end join back to string:

add_filter('admin_body_class', static function ($classes) {
    $classes = explode(' ', $classes);
    
    $classes = array_merge($classes, [
        'my-class-one',
        'my-class-two',
        'my-class-three',
        some_function(),
        another_function(),
    ]);

    return implode(' ', array_unique($classes));
});

Method 4

one of the hooks i use for editing WP admin/Dashboard admin_head

    function remove_screen_options(){ 

    $hideCSS = '<style>#screen-meta-links { display: none; }</style>';

}

Will put the css in your admin part

And by using class .wp-admin you could style the body part of admin.

Good luck


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x