WordPress如何判断页面层级 is_subpage

追格官方小助手/ 2022年02月21日/ WordPress/ 浏览 1275

在WordPress中,页面是分层级的。那么如何判断页面层级呢?

WordPress并没有提供现成的函数,不过,好消息是也容易判断。


global $post;
if (is_page() && $post->post_parent) {
    echo '这是一个子页面';
} else {
    echo '这不是子页面';
}


如果,经常要用,就封装一个函数:


function is_subpage()
{
    global $post;
    if (is_page() && $post->post_parent) {
        return $post->post_parent;
    } else {
        return false;
    }
}


要测试页面的父页面是否是特定页面,例如“About”,并给其设置一个不一样的Banner。


if (is_page('about') || '2' == $post->post_parent) {
    $bannerimg = 'about.jpg';
} elseif (is_page('learning') || '56' == $post->post_parent) {
    $bannerimg = 'teaching.jpg';
} elseif (is_page('admissions') || '15' == $post->post_parent) {
    $bannerimg = 'admissions.jpg';
} else {
    $bannerimg = 'home.jpg';
}


下面是一个函数,更轻松地执行上述测试。如果我们正在查看有问题的页面(即“关于”)或其子页面之一(即 ID 为“2”的父页面),此函数将返回 true。


function is_tree($pid)
{
    global $post;

    if (is_page($pid))
        return true;

    $anc = get_post_ancestors($post->ID);
    foreach ($anc as $ancestor) {
        if (is_page() && $ancestor == $pid) {
            return true;
        }
    }

    return false;
}

发表评论

暂无评论,抢个沙发...

客服 工单