2016-02-29 122 views
-1

如何获取每个页面的子页面,如果页面没有任何子项,那么必须显示正确的菜单。如何使函数获得页面祖先在wordpress中

例如:

  • 父页
    • 子页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); ?> 

回答

0

直接使用此功能

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

艾哈迈德,如果你只是想列出你目前所在的页面的孩子,你可以使用函数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); 
} 
?> 
+0

其实我要显示的每个页面的子页面。 例如: 父页面是“目的地” 目的地有7个子页面 我想仅在目的地页面上显示该7个子页面。 & 父父页工具 本页面没有任何儿童 ,所以我想对精确例如童车 的位置显示一个菜单,你可以检查我的网站上 [链接](HTTP:/ /thetraveling.net) –

+0

我已经为您更新了代码,以便在每个父页面上显示菜单。如果您在目的地页面上,则只列出目的地的孩子。此外,如果您是目标网页,则该网页的所有子女也将被列出。我希望这是你正在寻找的 –

1

这是默认的菜单调用WordPress的

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