Php 函数,如果当前页有子页,则返回true
我试图创建一个简单的函数来进行“状态测试”。目标是测试并查看当前正在查看的页面是否有子页面。使用此选项可以更改布局以容纳子页面。下面的代码似乎应该可以工作,但可惜没有骰子 有人看到我遗漏了什么吗编辑-注意这是在WordPress中Php 函数,如果当前页有子页,则返回true,php,wordpress,debugging,function,Php,Wordpress,Debugging,Function,我试图创建一个简单的函数来进行“状态测试”。目标是测试并查看当前正在查看的页面是否有子页面。使用此选项可以更改布局以容纳子页面。下面的代码似乎应该可以工作,但可惜没有骰子 有人看到我遗漏了什么吗编辑-注意这是在WordPress中 function is_subpage() { global $post; // load details about this page if ( is_page() && $post-&g
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
}
}看看这里:因为加载所有子页面只是为了做一个简单的检查,似乎有点耗费资源,所以我今天一大早就想到了这一点:
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;
}
您可以像使用(has_children())一样使用它,或者将其传递给post parent if(has_children($post-post_parent))——如果您使用的是get_posts/get_pages,而不是全局$post变量,则后者会很有用。我发现的所有示例(以及本示例)的问题在于,它们都假设我试图获取静态页面的$pageid。我真正想做的就是测试当前页面是否有子页面,然后返回true或false。嗯。。。如果(计数($children)!==0{//true code}或者{//false code}你试过这个
吗?>
这几乎是我能做到的唯一方法。你也可以使用
(from)