I tried with this code in functions.php
of my website's child theme.
add_filter('admin_body_class', 'custom_body_class');
function custom_body_class($classes) {
if (is_page(8))
$classes[] = 'home-admin-area';
return $classes;
}
But the class "home-admin-area" is not added. Is there any error in this code?
Edit 1: I used is_page()
function for backend page which was wrong. I tried with this also but it somehow did not work.
add_filter('admin_body_class', 'custom_body_class');
function custom_body_class($classes) {
if ($_GET['post']==8)
$classes[] .= ' new-class ';
return $classes;
}
I tried with this code in functions.php
of my website's child theme.
add_filter('admin_body_class', 'custom_body_class');
function custom_body_class($classes) {
if (is_page(8))
$classes[] = 'home-admin-area';
return $classes;
}
But the class "home-admin-area" is not added. Is there any error in this code?
Edit 1: I used is_page()
function for backend page which was wrong. I tried with this also but it somehow did not work.
add_filter('admin_body_class', 'custom_body_class');
function custom_body_class($classes) {
if ($_GET['post']==8)
$classes[] .= ' new-class ';
return $classes;
}
Use admin_body_class
both with global post_id and get_current_screen
function:
add_filter('admin_body_class', 'wpse_320244_admin_body_class');
function wpse_320244_admin_body_class($classes) {
global $post;
// get_current_screen() returns object with current admin screen
// @link https://codex.wordpress/Function_Reference/get_current_screen
$current_screen = get_current_screen();
if($current_screen->base === "post" && absint($post->ID) === 8) {
$classes .= ' home-admin-area';
}
return $classes;
}
You can also use $pagenow variable. It seems that this way would be preferable, because get_current_screen()
maybe undefined in some cases:
add_filter('admin_body_class', 'wpse_320244_admin_body_class');
function wpse_320244_admin_body_class($classes) {
global $post, $pagenow;
// $pagenow contains current admin-side php-file
// absint converts type to int, so we can use strict comparison
if($pagenow === 'post.php' && absint($post->ID) === 8) {
$classes .= ' home-admin-area';
}
return $classes;
}
admin_body_class
passes its values as a string, not an array. (This differs from body_class
which does pass an array. (See the documentation for admin_body_class
)
So what you need is:
add_filter('admin_body_class', 'custom_body_class');
function custom_body_class($classes) {
if (is_page(8))
$classes .= ' home-admin-area';
return $classes;
}
Note how it's adding as a string with a leading space.
However, not sure if this will work because I am wondering if you're using the correct filter for what you want to do. Your use of is_page()
makes me wonder - is this something you're doing in the admin? Or is this a front end thing?