Skip to content

Instantly share code, notes, and snippets.

@Jany-M
Last active June 6, 2021 16:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Jany-M/aff0885494d5327a53f4b454615b05bf to your computer and use it in GitHub Desktop.
Save Jany-M/aff0885494d5327a53f4b454615b05bf to your computer and use it in GitHub Desktop.
[WP] Add custom body classes for better CSS customization
<?php
function add_classes_to_body($classes) {
global $post;
// User Role
$user_info = get_currentuserinfo();
$classes[] = implode(' ', $user_info->roles);
// WPML
if ( function_exists('icl_object_id') ) {
$classes[] = ICL_LANGUAGE_CODE.' '.ICL_LANGUAGE_CODE.'-lang';
}
// Post Name
if (is_page() || is_singular()) {
$classes[] = $post->post_name;
}
// WooCommerce Product Categories
$section_terms = get_the_terms($post->ID, 'product_cat');
if ($section_terms && !is_wp_error($section_terms)) {
$classes[] = "is_term term";
foreach ($section_terms as $term) {
if ($term->parent > 0) {
$parentTerm = get_term($term->parent, 'product_cat');
$classes[] = "term-parent term-" . $parentTerm->slug;
} else {
$classes[] = 'term-' . $term->slug;
}
if ( count( get_term_children( $section_terms->term_id, 'product_cat' ) ) > 0 ) {
$classes[] = 'has-child';
} else {
$classes[] = 'no-child';
}
}
}
// Taxonomies
if (is_tax()) {
$qObj = get_queried_object();
$parentTermId = $qObj->parent;
if ($parentTermId) {
$parentTerm = get_term($parentTermId);
$classes[] = 'term-' . $parentTerm->slug;
} else {
$classes[] = 'term-' . $qObj->slug;
}
}
// Mobile
if(wp_is_mobile()) {
$classes[] = 'is-mobile';
}
// Logged in
if(is_user_logged_in()) {
$classes[] = 'logged-in';
}
// MU
/*$id = get_current_blog_id();
$slug = strtolower(str_replace(' ', '-', trim(get_bloginfo('name'))));
$classes[] = $slug;
$classes[] = 'site-id-' . $id;*/
return $classes;
}
add_filter('body_class', 'add_classes_to_body');
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment