Highlighting current item of custom post types’ sub pages, listed by wp_list_pages

The problem with this code is that the query is being altered and current_page_item is being lost. This is the part causing problems.

$post = get_post( $getid );
setup_postdata( $post );

If you comment out those two lines you’ll see that current_page_item appears.

There are also some secondary problems with this code that have no bearing on the main problem.

  1. <p></p> should not exist as a child element of <ul>. Only <li> is allowed.
  2. <h3>...</h3> also should not exist as a child element of <ul> for the same reasons as #1.
  3. The if statement setting the CSS class for the “Biography” link will return true on any single page, not just the parent page.
  4. wp_list_pages() outputs a list of <li>...</li> tag pairs so it doesn’t need to be wrapped with another pair of <li>...</li> tags.

The following code corrects all the issues.

<?php
$getid = get_post_top_ancestor_id(); 
global $post;
?>
<h3><?php echo get_the_title( $getid );?></h3>
<ul>
    <?php
    if ( $post->ID == $getid ) {
        $pg_li .= "current_page_item";
    } else {
        $pg_li .= "page_item";
    }
    ?>  
    <li class="<?php echo $pg_li; ?>">
        <a href="https://wordpress.stackexchange.com/questions/74034/<?php echo get_permalink( $getid ); ?>">BIOGRAPHY</a>
    </li>
    <?php
    $args=array(
        'post_type' => 'artists',
        'child_of' => $getid,
        'sort_column' => 'menu_order',
        'hierarchical' => 1,
        'title_li' => __('')
    );
    wp_list_pages( $args );
    ?>
</ul>

Leave a Comment