在Wordpress中显示直接父级子菜单

时间:2019-04-10 01:11:38

标签: php wordpress

我正在寻找在Wordpress模板上创建一个子菜单,该子菜单仅显示该父级中的其他子级。 I found a solution可以帮助我达到95%的目标,而我想不通如何在剩下的方法中做到这一点。任何帮助将不胜感激!

下面的代码中的解决方案将显示以下内容:

部分

  • 第1小节
  • 第2小节
    • 子页面
    • 子页面
  • 第3小节

我只想显示直接父级的子菜单,如下所示:

部分

  • 第2小节
    • 子页面
    • 子页面
<div class="sidebar-nav">

<h3><?php
    if ( 0 == $post->post_parent ) {
    the_title();
    } else {
    $parents = get_post_ancestors( $post->ID );
    echo apply_filters( "the_title", get_the_title( end ( $parents ) ) );
    }
?></h3>

<?php
function hierarchical_submenu($post) {
    $top_post = $post;
    // If the post has ancestors, get its ultimate parent and make that the top post
    if ($post->post_parent && $post->ancestors) {
        $top_post = get_post(end($post->ancestors));
    }
    // Always start traversing from the top of the tree
    return hierarchical_submenu_get_children($top_post, $post);
}

function hierarchical_submenu_get_children($post, $current_page) {
    $menu = '';
    // Get all immediate children of this page
    $children = get_pages('child_of=' . $post->ID . '&parent=' . $post->ID . '&sort_column=menu_order&sort_order=ASC');
    if ($children) {
        $menu = "\n<ul>\n";
        foreach ($children as $child) {
            // If the child is the viewed page or one of its ancestors, highlight it
            if (in_array($child->ID, get_post_ancestors($current_page)) || ($child->ID == $current_page->ID)) {
                $menu .= '<li class="sel"><a href="' . get_permalink($child) . '" class="sel"><strong>' . $child->post_title . '</strong></a>';
            } else {
                $menu .= '<li><a href="' . get_permalink($child) . '">' . $child->post_title . '</a>';
            }
            // If the page has children and is the viewed page or one of its ancestors, get its children
            if (get_children($child->ID) && (in_array($child->ID, get_post_ancestors($current_page)) || ($child->ID == $current_page->ID))) {
                $menu .= hierarchical_submenu_get_children($child, $current_page);
            }
            $menu .= "</li>\n";
        }
        $menu .= "</ul>\n";
    }
    return $menu;
}
?>

<?php
$submenu = hierarchical_submenu($post);
if ($submenu) {
    echo $submenu;
} else {
    // Do something else
}
?>

</div>

0 个答案:

没有答案