Goal: To change header images and alter nav-menu colors based on top level category of a Post or a Category archive page.
Requirements: Child cats (whether Post or Cat archive) should display the same as their top-level cats. Only needs to work for specified top cats; others are ignored (Posts have multiple hierarchies). Must work for a single Post or a Category archive page.
Solution: Add a body CSS class based on specified top-level cats (and their children); otherwise revert to a default class. Then let CCS do the rest (w/ class-specific background urls and color declarations.)
Question: The following works, but wondering if the code/tactic is sound?
The top-cats I'm trapping for have slugs of 'fire', 'energy', and 'land', also trolling for any of their descendants.
Code: In <head> of header.php:
<?php
// Add body class based on top-level category, or default to:
$cathead = 'cathead_home';
// Is Post (or Category archive) in 'X' category or a descendant of 'X'?
// Uses post_is_in_descendant_category() in functions.php; requires cat ID#.
// For readability using cat slug instead, and getting ID via get_term_by().
// To print, insert this PHP in HTML body tag: body_class($cathead);
if (is_category('fire') || in_category('fire') || post_is_in_descendant_category(get_term_by('slug','fire','category'))) {
$cathead = 'cathead_fire';
} elseif (is_category('energy') || in_category('energy') || post_is_in_descendant_category(get_term_by('slug','energy','category'))) {
$cathead = 'cathead_energy';
} elseif (is_category('land') || in_category('land') || post_is_in_descendant_category(get_term_by('slug','land','category'))) {
$cathead = 'cathead_land';
}
?>
Above requires this function in functions.php:
post_is_in_a_descendant_category() (from WP codex).
And this <body> tag in header.php:
<body <?php body_class($cathead); ?>>
As mentioned, it all works well. Just wondering if anyone sees improvements or mistakes? Thanks.