函数返回true,如果当前页有子页


Function to return true if current page has child pages

我试图创建一个简单的函数来做一个"状态测试"。目标是测试并查看正在查看的当前页面是否有任何子页面。使用它来改变布局以适应子页面。下面的代码看起来应该可以工作,但是唉,不行。

有人看到我错过了什么吗?编辑-注意这是在WordPress中。

function is_subpage() {
global $post;                              // load details about this page
if ( is_page() && $post->post_parent ) {   // test to see if the page has a parent
    return true;                                            // return true, confirming there is a parent
} else {                                   // there is no parent so ...
    return false;                          // ... the answer to the question is false
}

}

看这里:http://wordpress.org/support/topic/using-query-posts-to-list-child-pages?replies=7

因为加载所有的子页面只是为了做一个简单的检查似乎有点资源密集,所以我今天早上想到了这个:

function has_children($p = null) {
    global $post, $wpdb;
    $pid = ($p) ? $p : $post->post_parent;
    if ($pid) :
        $r = $wpdb->get_row("SELECT ID FROM $wpdb->posts WHERE post_parent = $pid LIMIT 1");
        if ($r) : return true; endif;
    else :
        return false;
    endif;
}

您可以像if (has_children())一样使用它,也可以将post父变量if (has_children($post-post_parent))传递给它——如果您使用get_posts/get_pages而不是全局变量$post,后者会很有用。