Expert Group of programming

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

Posted by : Heycode Tech | Posted in : wordpress, WordPress Functions | Oct 22,2015 | 2 comments

When we are creating a custom theme then we need to customize the design as per different pages. So we are trying to add the class in body tag. So for doing this,we are doing a lot of condition.But this is not good to write unnecessary code.


But wordpress have provided the function : body_class(); : which will automatically add the class in body tag .

Here is the syntax : 
Type -1 :
<body <?php body_class(); ?> >
Type - 2 :
<body <?php body_class("add_custom_Class"); ?> >
Note : You can add one argument also.

Output : 
page, page-template-{filename} and page-id-{number}

Customize this function :

Sometimes, we need to customize or add more classes as per requirement in function : body_class () : then it is also available. WordPress have provide the filter functionality for customize this class functionality.
Let’s see it.

//Customize the body class 
function heycodetech_customize_body_class( $classes ) {
global $post;
if ($post ) {
     $classes[] = $post->post_type . ' &nbsp;  ' . $post->post_name;
return $classes;
add_filter( 'body_class', 'heycodetech_customize_body_class' );

Now you can implement the anything with this filter.Currently I have implement the post type and post slug in body class. You can also implement according to own requirement.

Note : As per body_class, wordpress have provided the facility for adding the different class in loop also. The name of the function is : post_class() :


Author information - Heycode Tech

Every world can ask question and my website registered user give the suggestion.

See all posts by Author

Connect to author
  1. Pingback:Mastering the post_class() Function | HeyCode Tech

  2. WP DEV

    Nice, Simple and efficient .

    Keep updates.

Leave a Reply

Your email address will not be published. Required fields are marked *

About us

Heycodetech is a platform where you can ask any questions related to the programming like PHP,jQuery, MYSQL,HTML , CSS and more Here is the Expert group of programming.