WordPress: get post_parent title
I've created a custom sidebar that grabs the p开发者_开发知识库ost 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.
How can I output the post_parent title?
echo get_the_title( $post->post_parent );
or
echo get_the_title( X );
Where X is any valid post/page ID.
No need to get a complete post object just for one property.
It looks like you've already got the ID of the parent post, so you can just use this:
<?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)
Ref: http://codex.wordpress.org/Function_Reference/get_post
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); }?>
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() ) ) );
WordPress 5.7 introduces a new helper function to more easily fetch the parent post's ID:
get_parent_post()
This can also be used in conjunction with has_parent_post()
, so you could have something like looks like:
<?php if ( has_parent_post() ) : ?>
<a href="<?php the_permalink( get_parent_post() ); ?>">
<?php the_title( get_parent_post() ); ?>
</a>
<?php endif; ?>
Note that these functions accept a "child post ID" as a parameter, which defaults to the current post.
https://make.wordpress.org/core/2021/02/10/introducing-new-post-parent-related-functions-in-wordpress-5-7/
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
This should even work outside of the wordpress loop as well.
精彩评论