I’m pretty sure that I’m not the only person who is somewhat annoyed by the way WordPress handles the page-item classes for Page lists. Particularly if you’re like me and you use WordPress as a CMS. It would be a lot easier to deal with page-item-pagename than page-item-1. For one, page-item-pagename is easier to remember. Well, I bet you didn’t know that you can change that! Yep, that’s right. You can, and it’s all because of a relatively unknown hook that was introduced in WordPress 2.8 called page_css_class, and here is very quick and dirty way of changing the page item classes to match the pagename and not the page ID.
- Open or create a functions.php file in your theme directory.
- Then paste the code below into your functions.php file:
<?php add_filter('page_css_class', 'custom_page_css_class', 10, 2); /** * custom_page_css_class() * Hooks into page_css_class and modifies the page item class so that * it uses the name of the page instead of the id. * * @global int $id. The ID of the page being viewed. Needed to set current_page_item. * @param array $class. The page css class being modified, passed as an array from Walker_Page * @param object $page. The page object passed from Walker_Page * @return array Returns the new page css class. */ function custom_page_css_class($class, $page) { global $id; if ($page->ID == $id) /* checks if the page ID matches the current page and if it does, adds the current_page_item class */ $t = array( 'page_item', 'page-item-'.$page->post_name, 'current_page_item'); else $t = array( 'page_item', 'page-item-'.$page->post_name); return $t; } ?>
There you go! Yes, it’s that easy.
What the example does is it duplicates what’s happening in the WordPress source code but instead of using $page->ID, it’s using $page->post_name. It assembles the classes into an array and then returns it to be echo-ed out when the pagenav is generated. Note that $class isn’t used but it is necessary to have it as one of the parameters because WordPress passes it to the hook by default and we need the $page object in order to make the example work.
Happy coding!