我想在主题的侧栏中列出我当前页面的子页面。但是,我的侧栏(左侧)位于模板中循环之前,如果位于循环之前,则post->ID不会返回任何内容。
我的当前代码:
<?php
wp_list_pages(\'title_li=&child_of=\'.$post->ID);
?>
我读过一些关于调用全局变量来访问它的内容,但到目前为止还没有任何运气。任何帮助都将不胜感激。
我想在主题的侧栏中列出我当前页面的子页面。但是,我的侧栏(左侧)位于模板中循环之前,如果位于循环之前,则post->ID不会返回任何内容。
我的当前代码:
<?php
wp_list_pages(\'title_li=&child_of=\'.$post->ID);
?>
我读过一些关于调用全局变量来访问它的内容,但到目前为止还没有任何运气。任何帮助都将不胜感激。
。。。如果在循环之前,post->ID不会返回任何内容
一般来说,这是错误的。这个$post
对于大多数页面,在主题中循环开始之前就设置了变量。主查询将该变量“primes”到循环中的第一个post。也就是说,依赖循环外的这个变量并不是最可靠的方法。更可靠的是get_queried_object
.
$qobj = get_queried_object();
wp_list_pages(\'title_li=&child_of=\'.$qobj->ID);
因为get_queried_object
根据您所在的页面返回不同的信息,最好在使用之前检查页面类型。if (is_page()) {
$qobj = get_queried_object();
wp_list_pages(\'title_li=&child_of=\'.$qobj->ID);
}
或者检查对象本身。$qobj = get_queried_object();
if (isset($qobj->post_type) && \'page\' == $qobj->post_type) {
wp_list_pages(\'title_li=&child_of=\'.$qobj->ID);
}
这些只是例子。我不知道你的确切情况是什么。Try this:
// get the post id
$post_id = get_queried_object_id();
// get the children
$children = get_pages(\'child_of\' => $post_id);
//output them
if( count( $children ) != 0 ) {
echo "<ul>";
foreach ($children as $child) {
// if we only want children, not grandchildren
if ($child->post_parent == $post_id) {
echo "<li><a href=\\"" . get_permalink($child->ID) . "\\">";
echo $child->post_title;
echo "</a></li>";
}
}
echo "</ul>";
}
尽量使代码像
global $post;
var_dump($post);//test values in $post
wp_list_pages(\'title_li=&child_of=\'.$post->ID);
这里确实没有足够的信息来给出准确的答案,但如果您的怀疑是正确的,请尝试替换$post->ID
具有get_the_ID()
.
我在wordpress网站上需要一个“主页”菜单项,所以我创建了一个新页面并将其命名为“主页”,将其添加到我的主菜单项中,然后从阅读设置中选择“主页”作为首页。现在的问题是Home 正在使用page.php 而不是index.php. 我真的需要使用索引获取主页。php,因为我已经在索引中设计了首页。php你能告诉我如何使主页使用索引吗。php而不是页面。php