Home / css / Add custom body class for specific pages
  • How to Add custom body class for specific pages


    Adding this snippet to the functions.php of your wordpress theme will let you add a custom body class for specific pages. Add the second snippet to the header.php template replacing your default html body tag.

    ( click code to copy )

    wordpress snippet : PHP

    add_filter( 'body_class', 'my_neat_body_class');
    function my_neat_body_class( $classes ) {
         if ( is_page(7) || is_category(5) || is_tag('neat') )
              $classes[] = 'neat-stuff';
         return $classes;
    ( click code to copy )

    wordpress snippet : PHP

    <body <?php body_class(); ?>>

    ( WordPress codex functions, hooks, in this snippet. )

    body_class, is_page, is_category, is_tag, add_filter, _n,
  • Now that’s a very neat snippet for custom page layouts – awesome!

  • Very handy. Can something simular be done using page parent?

    • Sure you could do something like this, however if your pages only have a single parent the body_class will already add “page-parent” class to the body. This is only a problem if you have many child pages as each sub page may also be a parent page. What is it that you are trying to do?

  • Anonymous

    Is there anything you need to do after you add the class? I’m not seeing any way to add a custom class for a page…

    • Hi Trevor,
      Yes you will need to add the body_class(); function within the body tag I updated the snippet to avoid confusion.

  • Jhardy1974

    you this be combined with the other body class snippet so if the pages are not specified they default to have their own page as the class?

    • Should be able to just do

           if ( is_page(7) || is_category(5) || is_tag(‘neat’) ){
                $classes[] = ‘neat-stuff’;          }else{
                $classes[] = ‘other-class’;


  • Scott Dixon

    Thanks for this, I wanted a shorter body class name for a custom page template, using is_page_template (‘template-name.php’) and this worked perfect.

  • Michael

    Thanks a lot for this, really appreciated!

  • padrino431

    Works flawlessly for me, nice job!

  • where can i add class once above steps are done?

    • change the class in the code ‘neat-stuff’ to whatever you would like. You could even add
      multiple classes if need be.

  • thomas

    great! really helped me out.