Using WordPress ‘has_post_parent()’ PHP function

The has_post_parent() WordPress PHP function checks if a given post has a parent post.

Usage

has_post_parent( $post );

Custom example:

if ( has_post_parent( 42 ) ) {
    echo 'The post with ID 42 has a parent post.';
} else {
    echo 'The post with ID 42 does not have a parent post.';
}

Parameters

  • $post int|WP_Post|null Optional. Post ID or WP_Post object. Default is global $post. Default: null

More information

See WordPress Developer Resources: has_post_parent()

Examples

Check if the current post has a parent post

if ( has_post_parent() ) {
    echo 'The current post has a parent post.';
} else {
    echo 'The current post does not have a parent post.';
}

Display parent post title

if ( has_post_parent() ) {
    $parent_post = get_post( get_post()->post_parent );
    echo 'Parent post title: ' . $parent_post->post_title;
}

Display parent post permalink

if ( has_post_parent() ) {
    $parent_post_id = get_post()->post_parent;
    echo 'Parent post permalink: ' . get_permalink( $parent_post_id );
}

Check if a specific post has a parent post

$post_id = 42;

if ( has_post_parent( $post_id ) ) {
    echo "The post with ID {$post_id} has a parent post.";
} else {
    echo "The post with ID {$post_id} does not have a parent post.";
}

Display a message if a post has a parent post and is in a specific category

$category_slug = 'news';
$post_id = 42;

if ( has_post_parent( $post_id ) && has_category( $category_slug, $post_id ) ) {
    echo "The post with ID {$post_id} has a parent post and is in the {$category_slug} category.";
}

Tagged in

Leave a Comment

Your email address will not be published. Required fields are marked *