WordPress Help Articles

Add Slug as Body Class

Add Slug as Body Class

How to Use

Download > Install > Activate. That’s it!

Example

The page slug you are on, example: /contact-us/, would have a targetable CSS class of .contact-us. This page, /plugins/add-slug-as-body-class/, when activated, would have a body class of .plugins_add-slug-as-body-class.

Source

This code can be pasted into the functions.php file of your child theme or, download and install the plugin for simple code activation.

function viawebs_plugins_slug_body_class( $classes ) {
    $uri = $_SERVER['REQUEST_URI'];
    $uri = trim($uri, '/');
    $uri_with_underscores = str_replace('/', '_', $uri);
	$sanitized_uri = sanitize_title_with_dashes($uri_with_underscores);
    $classes[] = $sanitized_uri;
    return $classes;
}
add_filter( 'body_class', 'viawebs_plugins_slug_body_class' );

Via Webs Offers WordPress Hosting & Maintenance Services for Those That Prefer to Focus on Something Other Than the Technical Aspects

Our rollover development time lets you save unused hours for future assistance. Stay updated and optimized, with the flexibility to invest in new functionality.

Article Categories

Dive in to something specific you are wanting to learn more about.

Let's Get Started!