WordPress:获取 post_parent 标题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5198209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WordPress: get post_parent title
提问by Ryan
I've created a custom sidebar that grabs the post parent's pages:
我创建了一个自定义侧边栏,用于抓取帖子父页面:
query_posts("post_type=page&post_parent=6");
I'd like to grab the title of the post_parent (i.e. "About"). the_title
won't work because it's the title of the child pages.
我想获取 post_parent 的标题(即“关于”)。the_title
不起作用,因为它是子页面的标题。
How can I output the post_parent title?
如何输出 post_parent 标题?
回答by t31os
echo get_the_title( $post->post_parent );
or
或者
echo get_the_title( X );
Where X is any valid post/page ID.
其中 X 是任何有效的帖子/页面 ID。
No need to get a complete post object just for one property.
无需为一个属性获取完整的 post 对象。
回答by Demelziraptor
It looks like you've already got the ID of the parent post, so you can just use this:
看起来您已经获得了父帖子的 ID,因此您可以使用以下命令:
<?php
$parent_post_id = 6;
$parent_post = get_post($parent_post_id);
$parent_post_title = $parent_post->post_title;
echo $parent_post_title;
?>
(Insert your parent post id at $parent_post_id)
(在 $parent_post_id 中插入您的父帖子 ID)
回答by Thomas Maier
This is the clean and nice code you need:
这是您需要的干净漂亮的代码:
It is also save to use when there is more than one parent hierarchy level.
当存在多个父层次结构级别时,它也可以保存使用。
<?php
$current = $post->ID;
$parent = $post->post_parent;
$grandparent_get = get_post($parent);
$grandparent = $grandparent_get->post_parent;
?>
<?php if ($root_parent = get_the_title($grandparent) !== $root_parent = get_the_title($current)) {echo get_the_title($grandparent); }else {echo get_the_title($parent); }?>
回答by Dawid Urbanski
I know it's super old question, but in case anyone was looking for some nice one-liner. Here it is:
我知道这是一个非常古老的问题,但以防万一有人正在寻找一些不错的单线。这里是:
echo get_the_title( wp_get_post_parent_id( get_the_ID() ) );
If you want to keep title filter go with:
如果您想保留标题过滤器,请使用:
echo apply_filters( 'the_title', get_the_title( wp_get_post_parent_id( get_the_ID() ) ) );
回答by Enterprise Architect
I wrote this, it will grab the parent post and then echo the parents title and such. Have a look and let me know if it works for you.
我写了这个,它会抓取父帖子,然后回显父标题等。看看,让我知道它是否适合你。
https://gist.github.com/1140481
https://gist.github.com/1140481
This should even work outside of the wordpress loop as well.
这甚至应该在 wordpress 循环之外工作。