X

How to Customize the CSS for Specific Pages

Snippets by IsItWP

Do you want to customize the CSS for specific pages? Adding the parent page slug to the body_class is a great way to target a specific page with CSS. That way you can easily identify the class of the element you want to change.

Instructions:

All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:

add_filter('body_class','body_class_section');

function body_class_section($classes) {
    global $wpdb, $post;
    if (is_page()) {
        if ($post->post_parent) {
            $parent  = end(get_post_ancestors($current_page_id));
        } else {
            $parent = $post->ID;
        }
        $post_data = get_post($parent, ARRAY_A);
        $classes[] = 'parent-' . $post_data['post_name'];
    }
    return $classes;
}

Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.

If you liked this code snippet, please consider checking out our other articles on the site like: 62 best free WordPress blog themes or 7 best WordPress contact form plugins.

Comments   Leave a Reply

  1. Works beautifully in WordPress 3.9.1, thank you!

  2. Can this be adapted to add the top ancestor to the body class? So if I navigate to a grandchild page, I see not the parent slug, but the grandparent slug?

  3. When I use this, I still get all of the BS default classes added by WP. Is there a way to filter those out?

    1. Hi Jess, ill be posting a snippet monday that will provide a solution for this. 

  4. Thanks, exactly what I was looking for. One question – could this be adapted so that it outputs not only the parent page slug in the body classes, but also the current page slug as well? This would be useful for targeting sections in CSS, plus specific pages as well.

    1. I write something so  can post it in a new few days.

      1. Thanks, looking forward to it 🙂

Add a Comment Cancel reply

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!