Add the Page Slug to Body Class

This code snippet adds the page slug (post name) to the body class of WordPress pages. The body class is a set of CSS classes applied to the <body> element of a webpage and can be used to target specific pages or sections with CSS styles.

The code defines a function wpcode_snippet_add_slug_body_class that retrieves the global $post object. It then checks if the $post object is set, and if so, it appends the post type and post name (slug) to the $classes array.

The updated $classes array is then returned, and the body_class filter hook is used to apply the wpcode_snippet_add_slug_body_class function to the body_class filter.

By adding this code to your theme’s functions.php file, the page slug will be added as a CSS class to the <body> element, allowing you to target specific pages or sections with CSS styles based on their slugs.

PHP
function wpcode_snippet_add_slug_body_class( $classes ) {
	global $post;
	if ( isset( $post ) ) {
		$classes[] = $post->post_type . '-' . $post->post_name;
	}
	return $classes;
}
add_filter( 'body_class', 'wpcode_snippet_add_slug_body_class' );