Skip to main content
Login Join
Snippet · PHP

Add Custom Post Type to Body Class

Shared by Hiral solanki · September 9, 2026 · @body_class

Back to Snippets

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' );
Know a different way to do this? Add your approach as a variation so folks can compare them side by side.
Submit a variation

0 comments