The following function can be added to a WordPress theme or plugin. Its purpose is to add CSS classes to the body element of a webpage, which can be useful for targeting specific browsers/platforms or pages with CSS.
Let’s see an example:
<body class="liin-p-type-project liin-p-id-44 liin-is-browser-chrome liin-is-platform-macosx liin-is-locale-en_GB">
...
By incorporating the function, we can distinguish the following:
function liin_add_body_css_classes() {
$body_css_classes = [];
/* POST TYPE */
$post_type = get_post_type();
if ( $post_type != false ) {
$body_css_classes[] = 'liin-p-type-' . $post_type;
}
/* POST ID */
$post_id = get_the_ID();
if ( $post_id != false ) {
$body_css_classes[] = 'liin-p-id-' . $post_id;
}
/* TEMPLATE NAME */
$post_template = substr( basename( get_page_template() ), 0, -4);
if ( !empty($post_template) ) {
$body_css_classes[] = 'liin-p-' . $post_template;
}
/* BROWSER */
$browser = get_browser(null, true);
if ( is_array($browser) && array_key_exists('browser', $browser) ) {
$body_css_classes[] = 'liin-is-browser-' . str_replace(' ', '-', strtolower($browser['browser']));
}
/* PLATFORM */
if ( is_array($browser) && array_key_exists('platform', $browser) ) {
$body_css_classes[] = 'liin-is-platform-' . str_replace(' ', '-', strtolower($browser['platform']));
}
/* LOCALE */
if ( is_array($browser) && array_key_exists('platform', $browser) ) {
$body_css_classes[] = 'liin-is-locale-' . get_locale();
}
/* BOT AND CRAWLER */
if ( isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/bot|crawl|slurp|spider|mediapartners/i', $_SERVER['HTTP_USER_AGENT']) ) {
$body_css_classes[] = 'liin-is-agent-bot';
}
return $body_css_classes;
}
add_filter('body_class', 'liin_add_body_css_classes');
In WordPress, the body_class hook is a filter that adds classes to the body element of the page. This hook allows developers to modify the default classes added to the body element of a page, or to add custom classes based on various conditions or criteria.
If you have suggestions for improving the code, please send an email. It should be noted that the code's functionality is provided without any guarantee or responsibility.
WordPress nonces provide essential security measures against CSRF attacks.
To optimize the speed and efficiency of WordPress websites, developers often turn to WordPress Transients.
This website uses cookies to ensure you get the best experience on our website.