How to check if a WordPress post has child and siblings?

Viewed 1001

I need to hide a piece of code from showing up in certain pages. These pages are all child and siblings of the parent page with ID 8194.

To hide the code inside the child page I'm using if ( get_post_field( 'post_parent' ) != 8194 ), but the issue is that there are several sibling pages and that code isn't working on them, it only works in the child page.

This is my page hierarchy:

Parent page 1
- Child page 1
-- Sibling page 1
-- Sibling page 2
...
-- Sibling page 10

How can I hide the code in the sibling pages as well?

Thank you

3 Answers

If i understand correctly, you want to find the top-most parent.

For this I would use get_post_ancestors() which retrieves the IDs for the ancestors of a post (and returns a parents array): https://developer.wordpress.org/reference/functions/get_post_ancestors/

Try something like this:

global $post;
$parents = get_post_ancestors($post->ID);
// Get the 'top most' parent page ID, or return 0 if there is no parent:
$top_parent_id = ($parents) ? $parents[count($parents)-1]: 0;

if ($top_parent_id != 8194) {
...
}

** UPDATED CODE FOR OP'S SECOND QUESTION FROM THE COMMENTS: **

global $post;

// Don't show the code by default:
$show_code = false;

// This is an array of post ids where you want to show the code regardless of the parents id
$always_show_the_code_on_these_posts = array(111, 222, 333);

// Check if current post id is on the list:
if ( in_array($post->ID, $always_show_the_code_on_these_posts) ) {
    $show_code = true;
} else {
    // ...and only if it's not on the list run the previous test:
    $parents = get_post_ancestors($post->ID);

    // Get the 'top most' parent page ID, or return 0 if there is no parent:
    $top_parent_id = ($parents) ? $parents[count($parents)-1]: 0;

    if ($top_parent_id != 8194) {
        $show_code = true;
    }
}

if ($show_code) {   
...
}

You can use the wp_get_post_parent_id() function to check if the current page is a parent or a child by comparing it with the get_the_ID() function. is_page() here, is just a redundancy.

<?php
/**
* wp_get_post_parent_id
* Returns the ID of the post’s parent.
* @link https://developer.wordpress.org/reference/functions/wp_get_post_parent_id/
*
* get_the_ID
* Retrieve the ID of the current item in the WordPress Loop.
* @link https://developer.wordpress.org/reference/functions/get_the_ID/
*/
if( is_page() && wp_get_post_parent_id( get_the_ID() ) ):
  //child
  echo 'This is THE Child, Grogu';
else:
  //parent
  echo 'This is THE Mandalorian, Mando';
endif; ?>
Related