3 php wordpress if-statement parent
在我的第一个 WordPress 网站上工作,所以我确信这是一个非常基本的问题。我正在努力编写一个条件 php 语句,当页面是父页面的子页面时,该语句执行特定的操作。
例如,我不想只指定一个页面,如下所示,我想指定以“关于我们”页面作为父页面的所有页面:
<?php if (is_page('About Us')) echo 'Hello World!'; ?>
Run Code Online (Sandbox Code Playgroud)
我尝试过“child_of”函数,但它并不像我希望的那么简单。
当我使用下面的代码时,我收到语法错误 - 可能只是我不知道如何使用该函数:
<?php if (child_of('About Us')) echo 'Hello World!'; ?>
Run Code Online (Sandbox Code Playgroud)
有什么建议么?
将以下函数添加到您的functions.php主题文件中:
function is_tree($pid) { // $pid = The ID of the page we're looking for pages underneath
global $post; // load details about this page
$anc = get_post_ancestors( $post->ID );
foreach($anc as $ancestor) {
if(is_page() && $ancestor == $pid) {
return true;
}
}
if(is_page()&&(is_page($pid)))
return true; // we're at the page or at a sub page
else
return false; // we're elsewhere
};
Run Code Online (Sandbox Code Playgroud)
然后您可以使用以下内容:
if(is_tree('2')){ // 2 being the parent page id
// Do something if the parent page of the current page has the id of two
}
Run Code Online (Sandbox Code Playgroud)
参考: http: //codex.wordpress.org/Conditional_Tags