Wordpress:将活动类添加到$ parent_title [英] Wordpress: Add active class to $parent_title
问题描述
我正在显示侧栏菜单,其中列出了父页面和子页面。
I am displaying a sidebar menu listing Parent and child pages.
- 父母
- 第一页
- 第二页
- 第三页
- Parent
- Child page one
- Child page two
- Child page three
我的代码将类.current_page_item应用于活动子页面,但不应用于活动父页面。我希望父级在该页面上也有类.current_page_item。
My code is applying the class .current_page_item to the active child pages, but not to the active parent page. I would like the parent to have the class .current_page_item too when on that page.
<?php
if($post->post_parent)
$children = wp_list_pages("title_li=&child_of=".$post->post_parent."&echo=0");
else
$children = wp_list_pages("title_li=&child_of=".$post->ID."&echo=0");
if ($children) {
$parent_title = get_the_title($post->post_parent);?>
<ul id="sub">
<li><a href="<?php echo get_permalink($post->post_parent) ?>"><?php echo $parent_title;?></a></li>
<?php echo $children; ?>
</ul>
<?php } ?>
以下是输出内容的概念:
Here is an idea of what is being outputted:
<ul id="sub">
<li><a href="#">Parent</a></li>
<li class="page_item page-item-19 current_page_item"><a href="#">Child page</a></li>
<li class="page_item page-item-21"><a href="#">Child page</a></li>
<li class="page_item page-item-23"><a href="#">Child page</a></li>
</ul>
推荐答案
您应该使用 get_pages <或 wp_get_nav_menu_items 。任何返回一个post对象数组的WordPress函数。
You should use get_pages or wp_get_nav_menu_items. Any WordPress function that returns an array of post objects.
$children = wp_get_nav_menu_items( 'Main Menu' ); // dump to make sure this is an array of objects
echo "<ul id='sub'>";
foreach($children as $item) {
$class = '';
if ( $item->object_id == $post->post_parent ){
$class = 'current_page_ancestor';
} else if ( $item->object_id == $post->ID ){
$class = 'current_page_item';
}
echo "<li " . $class . "><a href='" . $item->url . "'>" . $item->title . "</a></li>";
}
echo "</ul>";
这将获取一个WordPress帖子数组,然后循环遍历它们。
This gets an array of WordPress posts, then loops through them.
如果当前迭代中的帖子ID与您正在查看的帖子的父主题相同,请添加类'current_page_ancestor。'
If the post ID in the current iteration is the same as the parent of the post you are viewing, add the class 'current_page_ancestor.'
如果当前迭代中的帖子ID与您正在查看的帖子相同,请添加类'current_page_item。'
If the post ID in the current iteration is the same as the post you are viewing, add the class 'current_page_item.'
这篇关于Wordpress:将活动类添加到$ parent_title的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!