Alter Body Class: How To Automatically Add Post And Page Name

Steven15 responsesWordPress
Advertise Here

Since a little time now, WordPress includes the function body_class() which applies some custom classes to the body of all the pages of your WordPress blog. This function being very helpful for styling your blog, you might want to push it even further and include your post names to make styling even easier.

To implement this functionality, you need to paste the following code in the functions.php file of your WordPress theme:

function dukeo_add_post_name_in_body_class( $classes ){
  if( is_singular() )
    global $post;
    array_push( $classes, "{$post->post_type}-{$post->post_name}" );
  return $classes;

add_filter( 'body_class', 'dukeo_add_post_name_in_body_class' );

Learn how I made $36,482 online in the past 12 months.

Simply input your best email below to get started.

Advertise Here


  1. Shad

    Oh man, this went way over my head haha. Anyone care to explain it to me a little more? Please? I have no idea about anything having to do with code…

    1. Anon

      Just try it and see what happens. If you don’t like it, then you can just take it off after. Bada-bing!

    2. Shad

      Alright, I guess it couldn’t hurt to try it. Man, I should really learn code…

    3. Anon

      Yeah, it would make life easier… but until then, you’re lucky that people with blogs posts these things!

  2. Liz

    Oooh-la-la! Fancy! I like :) I’m gonna go do this right meow!

  3. Mitch

    How do you think of these things? It’s brilliant!

  4. Buysellwordpress

    Excellent advice! I will try to implement it in real life! Thanks a lot for sharing!

  5. Webdesign Studio

    Very cool, I like these posts. Great new ideas.

  6. Dana

    So glad you post these. :)

  7. Sarah

    Style is everything!!

    1. Michelle

      Too true, and ladies know that best of all!

    2. Sarah

      So true, I feel like I have to dress my husband daily!

  8. Jony

    It would be nice to see what this will look like before I make changes to my site, but I guess I could try it!

  9. Mike

    These things just look like chicken-scratch letter-vomit to me, I can’t make any sense out of them. That’s why I hire people to do it for me! Or just copy and paste from here.

  10. Sad Music

    Very cool! Thanks!

Learn how I made $36,482 online in the past 12 months.

Simply input your best email below to get started.

No thanks, I have enough money