get_post_parent()
Gets the parent post object for the specified or current post in the loop.
If you need to check for the existence of a parent post, use the function has_post_parent().
Uses: get_post()
Used By: has_post_parent()
No Hooks.
Returns
WP_Post|null. WP_Post object of the parent post or null, if it does not exist.
Usage
get_post_parent( $post );
- $post(int/WP_Post/null)
- ID of the post or its object for which to get the parent post.
Default: global $post
Examples
#1 Display the title of the parent post
$child_post_id = 5;
$parent_post = get_post_parent( $post );
if ( $parent_post ) {
echo 'The title of the parent post: ' . get_the_title( $parent_post );
}
else {
echo 'The specified post does not have a parent post;
}
Changelog
| Since 5.7.0 | Introduced. |
get_post_parent() get post parent code WP 7.0
function get_post_parent( $post = null ) {
$wp_post = get_post( $post );
return ! empty( $wp_post->post_parent ) ? get_post( $wp_post->post_parent ) : null;
}