2016-02-29 117 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')); ?>