Skip to content Skip to menu

Dzikri Aziz

The D is silent — kind of.

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.

/**
 * Filter the list of CSS classes
 *
 * @param array   $css_class    An array of CSS classes to be applied
 *                              to each list item.
 * @param WP_Post $page         Page data object.
 * @param int     $depth        Depth of page, used for padding.
 * @param array   $args         An array of arguments.
 */
function kucrut_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', 'kucrut_page_css_class', 10, 4 );

Posted on in Tips & Tutorials.