2012-09-28 59 views
1

正如標題所暗示的,我想看看某個頁面有另一個頁面作爲父母,祖父母父母或偉大的盛大母公司等等如何檢查WordPress頁面是否有其他頁面作爲祖先?

要檢查父情況下,以下的作品

if (1 == $post->post_parent) { 

但對於祖先檢查時

if (1 == $post->post_ancestor) {

似乎並沒有工作。

任何想法?

感謝

回答

1

有一個在此支持沒有內置,但你可以使用這個輔助函數,把它放在你的functions.php:

function get_ancestor() { 
global $post; 
if ($post->post_parent) { 
    $ancestors=get_post_ancestors($post->ID); 
    $root=count($ancestors)-1; 
    $parent = $ancestors[$root]; 
} else { 
    $parent = $post->ID; 
} 

    return $parent; 
} 

它將返回的帖子的ID是祖先,所以你可以使用它像這樣:

if(1 == get_ancestor()) { 
    // Code here 
} 
1

除了通過「忍者」提供的功能,還要注意你的條件是不正確的:在「post_parent」包含ID如果當前頁面是父頁面,則返回0。

所以要問的實際情況,如果一個頁面有一個父:

if($page->post_parent != 0) 
    // page has a parent 
else 
    // page is a parent 
相關問題