Automatically adds the current WordPress post type as a CSS class to the `<body>` element using the `body_class` filter.
This is useful when working with custom post types and custom themes, allowing developers to target specific post types with CSS or JavaScript without adding classes manually to templates.
For example, a custom post type named `projects` will receive a class such as `post-type-projects`.
/**
* Add the current post type as a body class.
*
* @param array $classes Existing body classes.
* @return array
*/
function mytheme_add_post_type_body_class( $classes ) {
if ( is_singular() ) {
$post_type = get_post_type();
if ( $post_type ) {
$classes[] = 'post-type-' . sanitize_html_class( $post_type );
}
}
return $classes;
}
add_filter( 'body_class', 'mytheme_add_post_type_body_class' );