Add Snippet To Project
Sometimes in WordPress development, you might come across scenarios where you need to check if a parent page exists and then output that page’s ID. This can be useful for creating dynamic menus, breadcrumb trails, or for custom post types. If you’re new to this concept or not sure how to go about it, don’t worry, we’re here to guide you. In this article, we will be examining the process of determining if a parent page exists and how to return its ID.
function wpturbo_parent_page_id() {
global $post;
if ($post->post_parent) {
return $post->post_parent;
} else {
// Page doesn't have a parent
return false;
}
}
The code snippet we are looking at defines a function named wpturbo_parent_page_id(). This function is designed to return the ID of a parent page if it exists.
In more detail, this code establishes a WordPress feature known as global variables, global $post;. In WordPress, the $post global variable carries information about the currently queried object by WordPress, which could be a post, a page, or any custom post type.
Immediately after this, we proceed to an if statement which verifies whether the current $post object has a parent ($post->post_parent).
if ($post->post_parent) {
return $post->post_parent;
}
The $post->post_parent is a Wordpress built-in feature to get the parent ID of an object. If the parent exists, the function will return the ID of the parent page (return $post->post_parent;)
Then, if the page doesn’t have a parent, the function’s else block will be executed:
else {
// Page doesn't have a parent
return false;
}
This block essentially states that if the $post object doesn’t have a parent (it might be a parent itself or doesn’t have any hierarchical relationship), the function should return false.
Thus, wpturbo_parent_page_id() will return the ID of a parent page whenever the current page has a parent, or false if it doesn’t. This function could be useful to conditionally execute code based on whether the page has a parent, or to retrieve and use the data of the parent page.
