如何在wordpress中创建函数来获取页面祖先

时间:2016-02-29 02:28:08

标签: wordpress wordpress-theming

如何为每个页面获取子页面,如果页面没有任何子页面,则必须显示正确的菜单。

例如:

  • 家长页面
    • 儿童第1页
    • 子页面2

如果父母没有孩子,则显示任何菜单

现在我正在使用以下代码:

FUNCTION.PHP

function get_top_ancestor_id() {
global $post;
if ($post->post_parent) {
    $ancestors = array_reverse(get_post_ancestors($post->ID));
    return $ancestors[0];
}
return $post-> ID;

}

的header.php

<?php
$args = array(
        'child_of' => get_top_ancestor_id(),
        'title_li' => ''
    );

?>
<?php wp_list_pages($args); ?>

3 个答案:

答案 0 :(得分:1)

这是在wordpress中调用的默认菜单

  <?php wp_nav_menu( array( 'theme_location' => 'primary', 'menu_class' => 'nav-menu', 'menu_id' => 'primary-menu' ) ); ?>

答案 1 :(得分:0)

直接使用此功能

<?php wp_nav_menu( array( 'theme_location' => 'primary', 'menu_class' => 'nav-menu', 'menu_id' => 'primary-menu' ) ); ?>

答案 2 :(得分:0)

Ahmad,如果您只想列出您当前所在页面的子项,可以使用函数wp_get_post_parent_id(http://codex.wordpress.org/Function_Reference/wp_get_post_parent_id

因此,您的代码可能会简化为

<?php
global $post;
//If the page has children - print the list
if(wp_get_post_parent_id( $post->ID ))
{
    $args = array(
            'child_of' => wp_get_post_parent_id( $post->ID ),
            'title_li' => ''
    );
    wp_list_pages($args); 
}
else{
    $args = array(
            'child_of' => $post->ID,
            'title_li' => ''
    );
    wp_list_pages($args); 
}
?>