English 中文(简体)
WordPress帮助检查是否为父页
原标题:WordPress help with checking if parent page

我有这个功能,可以检查页面是否为父级:

function is_tree($pid) {      // $pid = The ID of the page we re looking for pages underneath
        global $post;         // load details about this page
        if(is_page()&&($post->post_parent==$pid||is_page($pid)))
               return true;   // we re at the page or at a sub page
        else
               return false;  // we re elsewhere
};

并像这样使用它来显示菜单:

<?php if (is_tree(6) || is_page(6)) { menu code here } ?>

然而,它只适用于直接的子页面,而不适用于子页面,例如。

domain.com/page1.0/page1.1/page1.1.1/

如果第1.0页的id为6,则菜单将出现在第1.0页和第1.1页,而不是第1.1.1页

如何修改代码,使树函数适用于指定页面ID以下的任何内容,而不仅仅适用于立即子页面。

谢谢

最佳回答

使用get_post_arcestors()

function is_tree( $pid ) {
    if ( is_page() ) {
        return ( get_the_ID() == $pid || in_array( $pid, get_post_ancestors( get_the_ID() ) ) );
    }

    return false;
}
问题回答

这样可以:

function is_tree( $pid ) {
global $post;         // load details about this page
if ( is_page() ) {
    return ( $post->ID == $pid || in_array( $pid, get_post_ancestors( $post->ID ) ) );
}

return false;

};





相关问题
Wrap stray text in <p> tags

Wordpress issue.. how do I wrap stray text in P tags? Example: Before- <div class = "content"> <img src = "hello.jpg"/> <h1>Introduction</h1> Hello! this is ...

Using jQuery Plugins with Wordpress

Having a bit of trouble using jQuery plugins (Superfish, jQuery UI, etc) using Wordpress. Everything works fine in my plain non-Wordpress site, but Wordpress seems to conflict with JQuery. There must ...

WordPress Data Storage Efficiency

I ve been asked to review a WordPress plugin of sorts and try to find ways of making it faster. The premise of this plugin is basically to store a bunch of users and shifts and appointments and ...

Why can t I properly style a blockquote in Wordpress?

On the design I just created for my website, I have a blockquote styled with two quote images using the span technique in css: blockquote { background-image: url(images/openquote.jpg); background-...

How does the WordPress <!--nextpage--> tag actually work?

What happens? I m guessing that somehow the post or page is parsed before displaying, and then just split into two methods? I can t seem to find any documentation on how the underlying <?php ...

Wordpress Plug-ins: How-to add custom URL Handles

I m trying to write a Wordpress Plug-in but can t seem to figure out how you would modify how a URL gets handled, so for example: any requests made for: <url>/?myplugin=<pageID> will ...

热门标签