wp_list_pages() not setting .current_page_item classes on custom post types

A rather frustrating bug that I became aware of when generating navigational menus for custom post types using wp_list_pages(). The list entries aren’t decorated with useful classes denoting the current item, the parent item, and ancestor(s).

Read about the issue here. Read about working solutions here. I’ve included the solution that I went with, in case you’re looking for a quick fix and no reading.

//Uses PHP 5.3+ anonymous functions. Use regular function if less than 5.3
add_filter('page_css_class', function($classes, $page) {
  global $post;
  if('YourCustomType' == get_post_type($post) && $post->ID == $page->ID)
    $classes[] = 'current_page_item';
  return $classes;
}, 10, 2);

7 thoughts on “wp_list_pages() not setting .current_page_item classes on custom post types

  1. Hi,
    when I added the above, I lost my current_page_item class on my normal page menus, called via wp_list_pages, but I fixed this, by removing “location’ == get_post_type($post) &&” from your filter and then it worked on both.

    Might help somebody else that comes across this great solution.

    Thank you for posting it.

    • My apologies, I had a few typos in my code that I have corrected now. I misspelled the variable name in the function body. The example now works properly and you’ll be able to get the existing WordPress classes along with the custom class.

  2. Thank you for this! I read many posts about the subject and tried multiple solutions before I got to your site. Pulled your code and it works!

  3. This is great, but it doesn’t cover the .current_page_ancestors class (which I use to color and collapse areas of the list). I’ve modified your code as follows to also add this class where appropriate, thought you might want to update your example:

    add_filter(‘page_css_class’, function($classes, $page) {
    global $post;
    if(‘YourCustomType’ == get_post_type($post) && $post->ID == $page->ID)
    $classes[] = ‘current_page_item’;
    if(‘YourCustomType’ == get_post_type($post) && in_array( $page->ID, get_post_ancestors( $post->ID )))
    $classes[] = ‘current_page_ancestor’;
    return $classes;
    }, 10, 2);

Leave a Reply

Your email address will not be published. Required fields are marked *


*