Add Snippet To Project
If you’re working on a WordPress website with multiple hierarchical pages, you may come across a situation where you need to retrieve the title of the parent page. Whether you want to display the parent page title in a breadcrumb navigation or use it for any other purpose, knowing how to get the parent page title can be incredibly useful. In this article, we’ll show you a simple and straightforward method to retrieve the title of the parent page in WordPress.
function wpturbo_get_parent_page_title() {
global $post;
// Check if the current page has a parent
if ( $post->post_parent ) {
$parent_page = get_post( $post->post_parent );
// Return the parent page title
return $parent_page->post_title;
}
// Return an empty string if there is no parent page
return '';
}
The code snippet above defines a function called wpturbo_get_parent_page_title()
. This function is used to retrieve the title of the parent page in WordPress.
To begin, the snippet makes use of the WordPress global variable $post
to access information about the current page. This variable holds the data of the page being currently accessed and provides us with the necessary information to retrieve the parent page title.
Next, the snippet checks if the current page has a parent page using the conditional statement if ( $post->post_parent )
. If the current page has a parent, the code block inside the conditional statement is executed.
Within the conditional statement, the snippet uses the get_post()
function to retrieve the parent page object based on the post ID which is stored in $post->post_parent
. This function takes the post ID as the parameter and returns the post object associated with that ID.
After obtaining the parent page object, the code snippet retrieves the post title of the parent page using the object property $parent_page->post_title
. This property holds the title of the parent page.
Finally, the function returns the parent page title using the return
statement. If there is no parent page, the function returns an empty string by default.
By using this code snippet, you can easily retrieve the title of the parent page in WordPress, which can be useful for various purposes such as displaying hierarchical navigation or creating custom templates.