Skip to content

Instantly share code, notes, and snippets.

@kailoon
Last active April 20, 2023 10:03
Show Gist options
  • Save kailoon/d4d22c9204909dff21eb to your computer and use it in GitHub Desktop.
Save kailoon/d4d22c9204909dff21eb to your computer and use it in GitHub Desktop.
Theme authors should avoid and not to hardcode custom body_class. Main reason for this is being able to remove the class when needed i.e. child themes.
<?php
// if there's a namespace, add it the body class
$classes[] = esc_attr( $theme_options['themename_namespace'] );
if ( isset( $post ) ) {
$classes[] = esc_attr( $post->post_type . '_' . $post->post_name );
}
if (is_single() ) {
foreach((wp_get_post_terms( $post->ID)) as $term) {
// add category slug to the $classes array
$classes[] = esc_attr( $term->slug );
}
foreach((wp_get_post_categories( $post->ID, array('fields' => 'slugs'))) as $category) {
// add category slug to the $classes array
$classes[] = esc_attr( $category );
}
}
@MihaiCraciun
Copy link

How should this be used exactly?
There is no mention of body_class();

Is this acceptable ?

function wp_body_classes( $classes ) {
    $classes[] = 'class-name';
      
    return $classes;
}
add_filter( 'body_class','wp_body_classes' );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment