wp_list_pages() for Custom Post Types

wp_list_pages() is a handy little function for displaying a list of hierarchical post type, and it works with custom post types too. Unfortunately, when used for a custom post type, the list items don’t have the necessary CSS classes for current page item/ancestors. Here’s a quick fix for this particular problem.

function kct_page_css_class( $css_class, $page, $depth, $args ) {
  if ( empty($args['post_type']) || !is_singular($args['post_type']) )
    return $css_class;

  $_current_page = get_queried_object();

  if ( in_array( $page->ID, $_current_page->ancestors ) )
    $css_class[] = 'current_page_ancestor';
  if ( $page->ID == $_current_page->ID )
    $css_class[] = 'current_page_item';
  elseif ( $_current_page && $page->ID == $_current_page->post_parent )
    $css_class[] = 'current_page_parent';

  return $css_class;
add_filter( 'page_css_class', 'kct_page_css_class', 10, 4 );


  1. Thanks a lot for your snippet! Very helpful and a real time saver!


    1. Dzikri Aziz 2012/05/30 at 1:47 am

      You’re welcome :)


  2. same here, I don’t understand why it doesn’t provide the classes by default !!


  3. When using wp_list_pages inside custom WP_Query with this code one must bring temporarily back the original value to global $post variable. Just learned it.


    1. Dzikri Aziz 2012/09/12 at 1:48 am

      Thanks for the info Jakub!


  4. Thank you very much!!!!


  5. Still works for WP 3.6.
    Quite a find! Thanks for posting this. Mwah.


    1. Dzikri Aziz 2013/10/16 at 5:24 am

      You’re very welcome!


Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>