questions

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

Rate this post

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

 

✔️Solution:

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) {
...
}

Leave a Reply

Your email address will not be published.

Back to top button