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">
CodePudding user response:
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")
CodePudding user response:
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/