Rob
Rob

Reputation: 6370

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

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 
}
?>

Upvotes: 40

Views: 92877

Answers (5)

Mo Abo
Mo Abo

Reputation: 1

You can use the get_pages() function. it takes an associative array as an argument. you can give that array 'child_of' => get_the_ID() to get the children of the current page, and if it hasn't any children the whole get_pages() function will return false, otherwise it will return a value that evaluates to true, which can be assigned to a variable to use as a conditional in an if statement.

$iAmParent = get_pages(array('child_of' => get_the_ID()));

Upvotes: 0

Alfredo-Rojas
Alfredo-Rojas

Reputation: 91

For Wordpress, you can simply check:

<?php 
  if (wp_get_post_parent_id(get_the_ID())) {
    echo "I am a child page";
  } 
?>

Upvotes: 7

Matthew T Rader
Matthew T Rader

Reputation: 176

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  )) : 
?>

Upvotes: 7

Queli Coto
Queli Coto

Reputation: 696

Put this function in the functions.php file of your theme.

function is_page_child($pid) {// $pid = The ID of the page we're looking for pages underneath
  global $post;         // load details about this page
  $anc = get_post_ancestors( $post->ID );
  foreach($anc as $ancestor) {
      if(is_page() && $ancestor == $pid) {
          return true;
      }
  }
  if(is_page()&&(is_page($pid)))
     return true;   // we're at the page or at a sub page
  else
      return false;  // we're elsewhere
};

Then you can use it:

<?php 
    if(is_page_child(100)) {
        // show image X 
    } 
?>

Upvotes: 7

Alex
Alex

Reputation: 38509

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
}
?>

Upvotes: 81

Related Questions