skip to Main Content

I want’s to add conditional body classes for index.php, page.php, category.php, tag.php

  • In index.php body class only want’s <body class"home"> In
    page.php body class only want’s <body class"page"> In category.php body class only want’s <body class"cat"> In tag.php body class only want’s <body class"tag"> In search.php body class only want’s <body class"search">

3

Answers


  1. If you write the body tag in your template (usually in the header.php file) as follows , these classes will be added automatically:

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

    (note that the category class will be "category", not "cat")

    Login or Signup to reply.
  2. You can use the body_class filter to accomplish this. Example below:

    add_filter("body_class", function($classnames) {
        $conditions = [
            "search" => is_search(),
            "home" => is_front_page(),
            "cat" => is_category(),
            "tag" => is_tag(),
            "page" => is_page()
        ];
    
        foreach ($conditions as $classname => $condition) {
            if ($condition) {
                return [ $classname ];
            }
        }
    
        // return default classnames if none of the above conditions are met
        return $classnames;
    });
    

    WordPress docs: https://developer.wordpress.org/reference/hooks/body_class/

    Login or Signup to reply.
  3. It would be best if you put "body_class" function in the body tag

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

    then you can add classes to your pages using "body_class" filter

    add_filter( 'body_class', 'custom_class' );
    function custom_class( $classes ) {
    if ( is_page_template( 'page-example.php' ) ) {
         $classes[] = 'example';
    }
    return $classes;
    }
    

    Your class will show up in this tag

    <body class="page page-id-2 page-parent page-template-default logged-in">
    

    For Reference: https://developer.wordpress.org/reference/hooks/body_class/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search