WPBeginner

Beginner's Guide for WordPress

  • Blog
    • Beginners Guide
    • News
    • Opinion
    • Showcase
    • Themes
    • Tutorials
    • WordPress Plugins
  • Start Here
    • How to Start a Blog
    • Create a Website
    • Start an Online Store
    • Best Website Builder
    • Email Marketing
    • WordPress Hosting
    • Business Name Ideas
  • Deals
    • Bluehost Coupon
    • SiteGround Coupon
    • WP Engine Coupon
    • HostGator Coupon
    • Domain.com Coupon
    • Constant Contact
    • View All Deals »
  • Glossary
  • Videos
  • Products
X
☰
Beginner's Guide for WordPress / Start your WordPress Blog in minutes
Choosing the Best
WordPress Hosting
How to Easily
Install WordPress
Recommended
WordPress Plugins
View all Guides

WPBeginner» Blog» Themes» How to Add Page Slug in Body Class of your WordPress Themes

How to Add Page Slug in Body Class of your WordPress Themes

Last updated on September 10th, 2012 by Editorial Staff
38 Shares
Share
Tweet
Share
Pin
Free WordPress Video Tutorials on YouTube by WPBeginner
How to Add Page Slug in Body Class of your WordPress Themes

If you work on WordPress themes on a regular basis, then it is probably best to familiarize yourself with these default WordPress generated CSS cheat sheet. Recently while working on a custom theme project, we found a need to customize certain items based on different pages. WordPress has these things called body classes which outputs the class page, page-template-{filename} and page-id-{number}. We couldn’t use page-id-{number} because page IDs change from development to deployment. We also didn’t want to create a custom page template with repetitive code. We knew that we can keep one thing the same on all of these pages which were page-slugs, so we decided to add page slugs in body class which allowed us to do all the customizations we wanted without any complications. In this article, we will show you how to add page slug in body class of your WordPress themes.

Because this is a theme-specific code, we recommend that you put it in your theme’s functions.php file.

//Page Slug Body Class
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' );

Now you will start seeing a new body class being outputted like this: page-{slug}. Use that class to override your default styles and customize elements for specific pages.

For example, if you were trying to modify a div with widgets class. You can have your css like this:

#sidebar .widgets{background: #fff; color: #000;}
.page-education #sidebar .widgets{background: #000; color: #fff;}

Hope you will find this tutorial helpful.

38 Shares
Share
Tweet
Share
Pin
Popular on WPBeginner Right Now!
  • Revealed: Why Building an Email List is so Important Today (6 Reasons)

    Revealed: Why Building an Email List is so Important Today (6 Reasons)

  • Checklist

    Checklist: 15 Things You MUST DO Before Changing WordPress Themes

  • How to Start Your Own Podcast (Step by Step)

    How to Start Your Own Podcast (Step by Step)

  • How to Properly Move Your Blog from WordPress.com to WordPress.org

About the Editorial Staff

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi. Trusted by over 1.3 million readers worldwide.

The Ultimate WordPress Toolkit

24 Comments

Leave a Reply
  1. jeba says:
    Jan 10, 2019 at 6:56 am

    Thanks. Its working

    Reply
    • WPBeginner Support says:
      Jan 10, 2019 at 11:31 am

      Glad our method worked for you :)

      Reply
  2. Bradley says:
    Jun 3, 2018 at 1:55 am

    Many thanks! Literally copied & pasted this code into my functions.php. Worked perfectly.

    Reply
  3. Alds says:
    Jul 9, 2017 at 9:37 pm

    How about using global $wp_query instead of $post? I’ve noticed that $post gets overwritten if you’ve run a wp_query before the functions.php gets executed.

    Reply
  4. Pete says:
    Apr 28, 2017 at 9:58 pm

    This needs a conditional statement to only apply it to single.php, not archive.php etc.

    Reply
  5. Chris says:
    Mar 19, 2017 at 4:08 pm

    How can I put the post-id in the body class?

    Reply
  6. Aaron McGraw says:
    Jun 9, 2016 at 4:56 am

    Awesome! Just what I needed. Thank you so much!

    Reply
  7. Daneil says:
    Nov 21, 2015 at 5:06 am

    Thank you for putting it out there, simple bit of code, but useful and allows you to write more human friendly css files, rather than classes based on ID. Cheers

    Reply
  8. Austin says:
    Sep 28, 2015 at 4:18 pm

    Thank you so much for this! I found out the hard way that page-id can change given different circumstances. This allows me to style individual pages without as much worry. :)

    Reply
  9. Kevin says:
    Jul 29, 2015 at 12:27 pm

    Many thanks for this. Had some problems initially due to the position of code in my stylesheet CSS but once moved to the bottom worked great. Just wish this was standard for WP as others have said and that i had known about this a long time ago

    Reply
  10. Tom McGinnis says:
    May 15, 2015 at 12:17 pm

    This code works quite well. I was finding, however, that search results would end up with the body class including the slug from the first item listed. Sometimes the first item would have styles that would override the styles for the search results page. Strange, huh!

    I figured out that if you put !is_search() inside the if statement, then this problem is eliminated. If anybody else runs into this problem, the fix is simple.

    Reply
    • Did you use &&? says:
      Aug 25, 2016 at 1:45 pm

      When you put in !is_search() –How did you write the code?

      Reply
  11. Murhaf Sousli says:
    Jan 30, 2015 at 11:41 am

    This’s exactly what I’m looking for, I pasted the code in function.php, but unfortunately there is no class added to body! any ideas?

    Reply
    • Asaf says:
      Feb 16, 2015 at 3:13 pm

      I have the exactly same issue

      Reply
      • Ahir Hemant says:
        Mar 24, 2015 at 10:28 am

        Hello, it working for me. send me your link so i can check.

        Thank you

        Reply
  12. WPBeginner Staff says:
    Dec 14, 2014 at 2:50 pm

    It is bundled with WordPress. However the front-end of your site is handled by themes that’s why it is left for theme authors to decide whether or not to use it.

    Reply
  13. MJ says:
    Dec 14, 2014 at 8:26 am

    Awesome! I wish this functionality was bundled with WP though

    Reply
  14. Miluette says:
    Jun 29, 2014 at 4:51 pm

    Thank you sooo much. Just what I needed.

    Reply
  15. Suat says:
    Feb 25, 2014 at 4:54 pm

    It’s great way for editing css.
    Thank you

    Reply
  16. Weerayut Teja says:
    Nov 26, 2013 at 9:20 pm

    You save my work time.
    Thanks Syed :)

    Reply
  17. Mike says:
    Jun 10, 2013 at 12:21 am

    Thanks for this. I just used it to create a quick plugin to add the slug and ancestor slugs to the body class. Anyone interested can get that here: https://github.com/bigmikestudios/bms-bodyclass-slug

    Reply
  18. Todd M. says:
    Oct 5, 2012 at 4:20 am

    This is a great snippet for all WordPress devs. Comes as standard in my theme setup now.

    Reply
  19. Gaurav Ramesh says:
    Sep 12, 2012 at 3:23 pm

    Thanks for this. Such small tips and tricks help a lot to beginners like me.

    Reply
  20. Randy Caruso says:
    Sep 11, 2012 at 1:41 pm

    Thanks for this – been stuck hacking myself to bits with the page-id and suffering the consequences.

    Reply

Leave a Reply Cancel reply

Thanks for choosing to leave a comment. Please keep in mind that all comments are moderated according to our comment policy, and your email address will NOT be published. Please Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

Over 1,320,000+ Readers

Get fresh content from WPBeginner

Featured WordPress Plugin
PushEngage
PushEngage
Increase your website traffic & revenue with push notifications. Learn More »
How to Start a Blog How to Start a Blog
I need help with ...
Starting a
Blog
WordPress
Performance
WordPress
Security
WordPress
SEO
WordPress
Errors
Building an
Online Store
Useful WordPress Guides
    • 7 Best WordPress Backup Plugins Compared (Pros and Cons)
    • How to Fix the Error Establishing a Database Connection in WordPress
    • Why You Need a CDN for your WordPress Blog? [Infographic]
    • 30 Legit Ways to Make Money Online Blogging with WordPress
    • Self Hosted WordPress.org vs. Free WordPress.com [Infograph]
    • Free Recording: WordPress Workshop for Beginners
    • 24 Must Have WordPress Plugins for Business Websites
    • How to Properly Move Your Blog from WordPress.com to WordPress.org
    • 5 Best Contact Form Plugins for WordPress Compared
    • Which is the Best WordPress Popup Plugin? (Comparison)
    • Best WooCommerce Hosting in 2020 (Comparison)
    • How to Fix the Internal Server Error in WordPress
    • How to Install WordPress - Complete WordPress Installation Tutorial
    • Why You Should Start Building an Email List Right Away
    • How to Properly Move WordPress to a New Domain Without Losing SEO
    • How to Choose the Best WordPress Hosting for Your Website
    • How to Choose the Best Blogging Platform (Comparison)
    • WordPress Tutorials - 200+ Step by Step WordPress Tutorials
    • 5 Best WordPress Ecommerce Plugins Compared
    • 5 Best WordPress Membership Plugins (Compared)
    • 7 Best Email Marketing Services for Small Business (2020)
    • How to Choose the Best Domain Registrar (Compared)
    • The Truth About Shared WordPress Web Hosting
    • When Do You Really Need Managed WordPress Hosting?
    • 5 Best Drag and Drop WordPress Page Builders Compared
    • How to Switch from Blogger to WordPress without Losing Google Rankings
    • How to Properly Switch From Wix to WordPress (Step by Step)
    • How to Properly Move from Weebly to WordPress (Step by Step)
    • Do You Really Need a VPS? Best WordPress VPS Hosting Compared
    • How to Properly Move from Squarespace to WordPress
    • How to Register a Domain Name (+ tip to get it for FREE)
    • HostGator Review - An Honest Look at Speed & Uptime (2020)
    • SiteGround Reviews from 4196 Users & Our Experts (2020)
    • Bluehost Review from Real Users + Performance Stats (2020)
    • How Much Does It Really Cost to Build a WordPress Website?
    • How to Create an Email Newsletter the RIGHT WAY (Step by Step)
    • Free Business Name Generator (A.I Powered)
    • How to Create a Free Business Email Address in 5 Minutes (Step by Step)
    • How to Install Google Analytics in WordPress for Beginners
    • How to Move WordPress to a New Host or Server With No Downtime
    • Why is WordPress Free? What are the Costs? What is the Catch?
    • How to Make a Website in 2020 – Step by Step Guide
Deals & Coupons (view all)
Connections Pro
Connections Pro Coupon
Get 15% OFF on Connections Pro WordPress directory plugin.
SeedProd Logo
SeedProd Coupon
Get 50% OFF SeedProd Coming Soon Page plugin for WordPress.
Featured In
About WPBeginner®

WPBeginner is a free WordPress resource site for Beginners. WPBeginner was founded in July 2009 by Syed Balkhi. The main goal of this site is to provide quality tips, tricks, hacks, and other WordPress resources that allows WordPress beginners to improve their site(s).
Join our team: We are Hiring!

Site Links
  • About Us
  • Contact Us
  • FTC Disclosure
  • Privacy Policy
  • Terms of Service
  • Free Blog Setup
  • Free Business Tools
Our Sites
  • OptinMonster
  • MonsterInsights
  • WPForms
  • SeedProd
  • Nameboy
  • RafflePress
  • Smash Balloon

Copyright © 2009 - 2021 WPBeginner LLC. All Rights Reserved. WPBeginner® is a registered trademark.

Managed by Awesome Motive | WordPress hosting by SiteGround | WordPress CDN by MaxCDN | WordPress Security by Sucuri.