Don’t hesitate to contact us if you have any feedback.

WordPress – Add page specific body classes

In web design, CSS plays a crucial role in customizing the look and feel of individual pages. To give you more power over styling, the following PHP snippet allows you to dynamically add the page slug as a class to the <body> tag of each page on your WordPress site.

The Code

<?php 

function add_slug_body_class($classes) {
    global $post;
    if (isset($post)) {
        $classes[] = $post->post_type . '__' . $post->post_name;
    }

    return $classes;
}
add_filter('body_class', 'add_slug_body_class');

How It Functions

When you add this function to your theme’s functions.php file, it hooks into the body_class filter provided by WordPress. It then appends a new class to the body tag that combines the post type and the post slug, separated by two underscores. For example, if you have a page with the slug “about-us,” the body tag will include the class “page__about-us.”

Advantages of Using Page Slugs as Body Classes

  • Targeted Styling: Apply unique styles to specific pages without affecting others.
  • Improved Organization: Easily manage your CSS by knowing exactly which styles apply to which page.
  • Theme Customization: Tailor your theme to better suit the content and structure of your site.

By leveraging the dynamic nature of WordPress, this code snippet enhances your ability to create a more customized and visually coherent website.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *