Since your menu is most likely displayed before The Loop, you’ll need to use a bit of trickery.
get_the_category() can be used to fetch a single post’s categories. It’s supposed to be called in The Loop. but you can get around that like this:
<?php
if (is_single()) {
// we're looking at a single post
$this_id = $wp_query->post->ID;
$cats = get_the_category($this_id);
} // done with the is_single check
Then you can use something like the following for $cats :
<?php
foreach ($cats as $cat) {
if (2 == $cat->cat_ID) {
// highlight the proper menu item
} elseif (3 == $cat->cat_ID) {
// highlight the proper menu item
} // end if
} // end foreach
Let us know if that helps you!
It looks great, but not being a php novice I’m unsure of how that would correctly integrate into my existing php conditional statements. Can you give me a small example of how it would integrate with my code?
Thanks for your help thus far, it is much much appreciated 🙂 Everyday I work with wordpress I pick up a new bit of knowledge with PHP I feel like.
Robbiw
Ok, it is actually working! Getting close, I can view a post and highlight the menu item, the only problem is when I am viewing a category, archive, custom page or home page I get the following error at the top of my site:
Warning: Invalid argument supplied for foreach() in /home/.haman/liquilife/tonicnews.com/go/wp-content/themes/tonicnews/header.php on line 29
The page renderes fine and the dynamic menu highlighting still works, just that ugly error message. This is what I’ve got so far:
<?php
if (is_single()) {
$this_id = $wp_query->post->ID;
$cats = get_the_category($this_id);
} ?>
<?php
foreach ($cats as $cat) {
if (5 == $cat->cat_ID) { $current = 'two'; }
elseif (1 == $cat->cat_ID) { $current = 'three'; }
elseif (3 == $cat->cat_ID) { $current = 'four'; }
} ?>
<?php
if ( is_home() ) { $current = 'one'; }
elseif ( is_category('5') ) { $current = 'two'; }
elseif ( is_category('1') ) { $current = 'three'; }
elseif ( is_category('3') ) { $current = 'four'; }
elseif ( is_page('gallery') ) { $current = 'five'; }
elseif ( is_page('junctions') ) { $current = 'six'; }
elseif ( is_page('contact') ) { $current = 'seven'; }
?>
<style type="text/css">
#mainnav li a#<?php echo $current; ?> {
background: #000000;
color:#FFFFFF;
}
</style>
The fix is simple: make sure the foreach loop occurs inside the if (is_single()) block, like this:
<?php
if (is_single()) {
$this_id = $wp_query->post->ID;
$cats = get_the_category($this_id);
foreach ($cats as $cat) {
if (5 == $cat->cat_ID) { $current = 'two'; }
elseif (1 == $cat->cat_ID) { $current = 'three'; }
elseif (3 == $cat->cat_ID) { $current = 'four'; }
} // end foreach
} //end if (is_single())
?>
Awesome, thank you Skippy for your help, it is much appreciated!