Php – Checking whether post_parent = 0 in WordPress

phpwordpress

I am creating a site using WordPress using a theme which has this PHP at the top of each page and I am confused as to what it does.

<?php 
global $post;
global $wp_query;
if ( $post->post_parent != 0 ) {
    $thePostID = $post->post_parent;
} else {
    $thePostID = $wp_query->post->ID;
};
?>

I was just wondering if anyone could explain exactly what this does? I think it checks to see if the post_parent id is 0 which isn’t allowed in WordPress and sets the post id to the post_parent but I’m not 100% sure.

Best Solution

I think it checks to see if the post_parent id is 0 which isn’t allowed in WordPress

The $post->post_parent is allowed to be 0. If the value is 0, it simply means that the page is a top level page.

A page that has a $post->post_parent other than 0, is a child of another page.

For example, take this page structure as an example:

id      page_title    post_parent
1       Home          0
2       About         0
3       Staff         2
4       History       2
5       Contact       0

The resulting page/menu structure would be:

  • Home
  • About
  • Staff
  • History
  • Contact

The code in question:

if ($post->post_parent != 0) {
    $thePostID = $post->post_parent;
} else {
    $thePostID = $wp_query->post->ID;
}

I'm not sure why your theme might have the code, but a possible reason might be to get a menu related to the current page. If you're viewing the top level page (i.e. $post->post_parent == 0), then it would show all child pages, or if you're viewing a sub page, the menu might show all sibling pages.

A sample menu generated using this method

Add this to your functions.php file so it's accessible throughout the theme.

/**
 * Get top parent for the current page
 *
 * If the page is the highest level page, it will return its own ID, or
 * if the page has parent(s) it will get the highest level page ID. 
 *
 * @return integer
 */
function get_top_parent_page_id() {
    global $post;
    $ancestors = $post->ancestors;

    // Check if the page is a child page (any level)
    if ($ancestors) {
        // Get the ID of top-level page from the tree
        return end($ancestors);
    } else {
        // The page is the top level, so use its own ID
        return $post->ID;
    }
}

Add this code to your theme where you want to display a menu. You will need to customise it to suit your particular needs, but it gives you an example of why someone might use the code you asked about.

// Get the highest level page ID
$top_page_id = get_top_parent_page_id();

// Display basic menu for child or sibling pages
$args = array(
    'depth'        => 1,
    'title_li'     => FALSE,
    'sort_column'  => 'menu_order, post_title',
    'child_of'     => $top_page_id
);
echo wp_list_pages($args);