How to highlight a currently selected item/section in WordPress with CSS (maybe PHP too)?

I would like to have the currently displayed Page or Recent post highlighted with CSS.

Something like this:

Read More

PAGES:

…Home

About <–current page

…Contact

RECENT POSTS:

post1 <– current post the user is seeing.

…post2

…post 3

I used to accomplish that assigning an unique id to the body tag to make each page unique for CSS, and change the color of the navigation link.

In word press, for instance, all the recent posts are using the same body so I can’t figure out how to do it.

Any suggestions?

Related posts

Leave a Reply

2 comments

  1. If you’re using wp_list_pages(), you can use the classes current_page_item, current_page_ancestor and current_page_parent to target the active nodes.

    Otherwise a bit of manual labour is at stake – you could echo the current slug on the body tag, either as a class or ID, or print an ‘active’ class on the navigation item if it’s the current page;

    function active_class($page)
    {
        if (is_page($page))
            echo ' class="active"';
    }
    

    And put into play;

    <ul>
        <li<?php active_class('about'); ?>><a href="/about/">About</a></li>
        <li<?php active_class('contact'); ?>><a href="/contact/">Contact</a></li>
    </ul>
    
  2. For the completeness of discussion, it’s important to note that since wordpress 3.0, highlighting the current page is possible with CSS. No need for javascript. The current menu item has the current-menu-item class (here is a full tutorial.

    It’s important to note that if a menu item has sub-menus, and the current page is on a sub-menu, the class will be added to both the current menu item and the current sub-menu item within that menu.

    So here is what I’ve implemented on my site:

    .menu > ul > li.current-menu-item {text-shadow: 2px 2px grey;}
    .menu ul.sub-menu > li {text-shadow: none;} 
    .menu ul.sub-menu > li.current-menu-item {text-shadow: 2px 2px grey;}
    

    Take this as a starting point and enjoy!