Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a page is a parent or if it's a child page?

Tags:

php

wordpress

Is it possible to check if a page is a parent or if it's a child page?

I have my pages set up like this:

-- Parent

---- Child page 1

---- Child page 2

etc.

I want to show a certain menu if it's a parent page and a different menu if it's on the child page.

I know I can do something like below but I want to make it a bit more dynamic without including specific page ID's.

<?php if ($post->post_parent == '100') { // if current page is child of page with page ID 100    // show image X  } ?> 
like image 210
Rob Avatar asked Dec 17 '12 15:12

Rob


People also ask

Is Page A parent WordPress?

Parent Page Using Parent Pages is a good way to organize your Site Pages into hierarchies. A parent page is a top-level page, with child pages nested under it. For example, you could have an “About” page as a top level or parent page, and then have child pages “Life Story” and “My Dogs” under it.

What is a parent page and child page?

A child page can only have one parent page, but a parent page can have multiple child pages. So a child page can have sibling pages on the same level. For instance, on a company website, a Team and Mission page are probably child pages of the About us page. And, in that case, the Team and Mission page are siblings.

How do I find parent post ID in WordPress?

wp_get_post_parent_id( int|WP_Post|null $post = null Returns the ID of the post's parent.

What is a child's page?

A child page is a page that “lives” in hierarchy underneath another page (the parent). In the example below, both “Our Team” and “Company History” are child pages of “About”. Home.


2 Answers

You can test if the post is a subpage like this:
*(from http://codex.wordpress.org/Conditional_Tags)*

<?php  global $post;     // if outside the loop  if ( is_page() && $post->post_parent ) {     // This is a subpage  } else {     // This is not a subpage } ?> 
like image 140
Alex Avatar answered Oct 16 '22 01:10

Alex


I know this is an old question but I was searching for this same question and couldn't find a clear and simple answer until I came up with this one. My answer doesn't answer his explanation but it answers the main question which is what I was looking for.

This checks whether a page is a child or a parent and allows you to show, for example a sidebar menu, only on pages that are either a child or a parent and not on pages that do not have a parent nor children.

<?php     global $post;        $children = get_pages( array( 'child_of' => $post->ID ) );    if ( is_page() && ($post->post_parent || count( $children ) > 0  )) :  ?> 
like image 40
Matthew T Rader Avatar answered Oct 16 '22 01:10

Matthew T Rader