I don’t know why, but for some reason, I thought WordPress already included the slug of a post or page in either the function
post_class(). Doing some work over this weekend I realized that’s not the case, but luckily, it’s very easy to do.
post_class() serve as a way for you to easily customize a page’s CSS based on attributes of the page being viewed. They will output things like the post ID, the custom post type, if the page is the blog, home, or front page, and more. One thing it does not include, however, is the post slug. This could be useful if you want to style each of your posts a certain way, or in a more likely scenario, style each page a certain way. If you want to do this, the code is fairly straight forward; both functions accept an option argument: a string of your own classes. We use that combine with the $post array, like so:
<?php body_class($post->post_name); ?>
or, if you want to do it on a post-by-post basis:
<?php post_class($post->post_name); ?>
Note the latter must be used inside the Loop. Using this, if you have a page named, “Services” with the slug services, the output would look something like this:
<body class="page page-id-108 page-parent page-template-default services">
Now you can use the .services (or whatever) class name to do some custom stuff instead of needing to know the page or post ID.