【问题标题】:How to display sub child pages only when on direct parent page?如何仅在直接父页面上显示子子页面?
【发布时间】:2014-10-24 20:03:32
【问题描述】:

我有一个非常正常的页面层次结构,如下所示:

- Main page
- - Child page
- - Child page 2
- - Child page 3
- - - Sub child page
- - - Sub child page 2
- - Child page
- - Child page
- - - Sub child page
- Main page 2
- - Child page
...

当我在任何页面上时,我想在侧边栏上显示一个包含所有子页面的菜单,但不是主页。 这个,我可以用我从另一个答案中得到的这组论点来做:

<?php 
$child_of_value = ( $post->post_parent ? $post->post_parent : $post->ID );
$depth_value = ( $post->post_parent ? 2 : 1 );
$args = array( 
        'depth' => $depth_value,
        'sort_column' => 'menu_order', 
        'sort_order' => 'asc',
        'title_li' => '',
        'child_of' => $child_of_value,
        'echo' => 0
);

      $children = wp_list_pages($args);
?>

这样,菜单中会显示属于同一主页的所有子页面。问题在于子子页面。我只想在他们的直接父页面中显示它们,但与所有其他页面一起显示。

因此,例如,如果我在一个没有任何其他子页面的子页面中,它将如下所示:

- - Child page <---
- - Child page 2
- - Child page 3
- - Child page
- - Child page

如果我在第三个,它会看起来像这样:

- - Child page
- - Child page 2
- - Child page 3 <---
- - - Sub child page
- - - Sub child page 2
- - Child page
- - Child page

如果我在子页面中,我会显示相同的内容。 有什么办法可以通过修改参数来实现这一点?

【问题讨论】:

    标签: wordpress


    【解决方案1】:

    不只是通过修改参数,而是可以通过 CSS 来实现。如果您像正在做的那样操纵深度,它将为菜单中的所有链接获得该深度。这对于深度 0 来说很好,但是当您达到深度 1 及以上时,它将显示所有具有子页面的子菜单。

    相反,这里是生成菜单的代码,该菜单列出了所有深度的顶级页面(包括孙子、曾孙等)的所有子页面,然后可以根据当前页面隐藏或显示:

    <?php
        global $post;
        $parent_id = wp_get_post_parent_id( $post->ID );
        $top_parent = $post->ID;
        while( $parent_id ){
            if( $parent_id > 0 ){
                $top_parent = $parent_id;
            }
            $parent_id = wp_get_post_parent_id( $parent_id );
        }
        $args = array( 
            'sort_column' => 'menu_order', 
            'sort_order' => 'asc',
            'title_li' => '',
            'child_of' => $top_parent,
            'echo' => 1
        );
        $children = wp_list_pages($args);
    ?>
    

    在您的样式表中,您可以使用这些:

    .page_item_has_children > .children {display: none;} /*hides the submenu*/
    .page_item_has_children.current_page_item > .children,
    .page_item_has_children.current_page_ancestor > .children {display: block;} /*shows the submenu for the current page or when on its subpages /*
    

    【讨论】:

    • 谢谢,这是完美的,而且比我预期的要好得多。正是我需要的。为了将来参考,我只想指出参数“echo”的值应该为 0,因为您将 wp_list_pages 结果分配给变量
    • 我的错 - 我在测试时将其设置为 1,但忘记将其设置回来。很高兴它能满足您的需求!
    • @Joe-NewNine - 是否有与上述完全相同的操作,但包括侧栏中的 $top_parent ?谢谢!
    • 不是自动的,但是你有顶级父 id 并且你的 $children 变量有项目包裹在 li 标签中,所以你可以这样做:
      或类似的东西。你有你需要的东西,所以你可以在这里打印任何你想要的东西。有意义吗?
    • @Joe-NewNine - 你是男人中的王子。是的,有道理,谢谢。
    猜你喜欢
    • 2015-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-28
    • 1970-01-01
    相关资源
    最近更新 更多