The below code is for listing the custom post types itself and its children in the sidebar.
The code works great but does not highlight the sub pages.
In functions.php
:
if(!function_exists('get_post_top_ancestor_id')){
/**
* Gets the id of the topmost ancestor of the current page. Returns the current
* page's id if there is no parent.
*
* @uses object $post
* @return int
*/
function get_post_top_ancestor_id(){
global $post;
if($post->post_parent){
$ancestors = array_reverse(get_post_ancestors($post->ID));
return $ancestors[0];
}
return $post->ID;
}}
and adding this code to the sidebar:
<ul>
<?php
$getid=get_post_top_ancestor_id();
#echo $getid;
global $post;
$post=get_post($getid);
setup_postdata($post);
?>
<?php
if (is_single($post->ID)) {$pg_li .="current_page_item";}
else {
$pg_li .="page_item";}
?>
<h3><?php the_title();?></h3>
<p></p>
<li class="<?php echo $pg_li; ?>">
<a href="https://wordpress.stackexchange.com/questions/74034/<?php the_permalink(); ?>">BIOGRAPHY</a>
</li>
<li class="<?php echo $pg_li; ?>">
<?php
$args=array(
'post_type'=>'artists',
'child_of'=>$getid ,
'sort_column'=>'menu_order',
'hierarchical' => 1,
'title_li'=>__('')
);
wp_list_pages( $args );
wp_reset_query();
?></li>
</ul>
I am not familiar with PHP, and a friend helped me to write this code. So what am I missing to highlight the current sub menu of that custom post type?
2 Answers
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.
<p></p>
should not exist as a child element of<ul>
. Only<li>
is allowed.<h3>...</h3>
also should not exist as a child element of<ul>
for the same reasons as #1.- The
if
statement setting the CSS class for the “Biography” link will return true on any single page, not just the parent page. 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>