Last active
June 6, 2021 16:20
-
-
Save Jany-M/aff0885494d5327a53f4b454615b05bf to your computer and use it in GitHub Desktop.
[WP] Add custom body classes for better CSS customization
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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