3

Using this piece of code you can show content depending if it's a child-page or not:

<?php
global $post;

if ( is_page() && $post->post_parent ) : ?>
This is a child-page.

<?php else : ?>
This is a parent-page.

<?php endif; ?>

But I would like to add one more statement, so that I could have different content if it's a parent-page that has a child, or a parent-page that hasn't. Would something like this below work? If yes, what would "XXX" be?

<?php
global $post;

if ( is_page() && $post->post_parent ) : ?>
This is a child-page.

<?php elseif ( is_page() && XXX ) : ?>
This is a parent-page (with one or more children)

<?php else : ?>
This is a parent page without children.

<?php endif; ?>

Thanks in advance!

3 Answers 3

8

I ended up using this code:

<?php
global $post;
$children = get_pages( array( 'child_of' => $post->ID ) );

if ( is_page() && $post->post_parent ) : ?>
This is a child-page.

<?php elseif ( is_page() && count( $children ) > 0 ) : ?>
This is a parent-page (with one or more children)

<?php else : ?>
This is a parent page without children.

<?php endif; ?>
2

You could also create your own conditional tag. In functions.php add:

function my_is_parent() {
    global $post;

    $children = get_pages('child_of='.$post->ID);
    if( count( $children ) > 0 ) {
        $parent = true;
    }

    return $parent;
}

And in your IF instead of XXX add: my_is_parent()

You could of course name it something else instead of "my_is_parent" if you want. Not sure on this part though, but I guess that it´s not really feature proof to use "is_parent" if it gets included in core one day.

3
  • Shouldn't this return $parent = true, a boolean value rather than text?
    – Trevor
    Sep 8, 2015 at 1:51
  • @Trevor yes you are right. Though it works with the text value as well, but I updated this 3 years old answer now :)
    – jzatt
    Sep 8, 2015 at 8:04
  • Still a valid answer 7 years later. Apr 14, 2019 at 13:21
0

you can achive that with using

global $post;

$args = array (
    'parent' => $post->ID
);

$children = get_pages( $args );

if ( is_page() && $post->post_parent ) : ?>
This is a child-page.

<?php elseif ( is_page() && count( $children ) > 0 ) : ?>
This is a parent-page (with one or more children)

<?php else : ?>
This is a parent page without children.

<?php endif; ?>

and using count( $children ) > 0 instead of your XXX

2
  • Could you show the full code? Thanks!
    – nicolas
    Nov 22, 2012 at 14:01
  • Hi @nicolas, filled in the full code for you.
    – fischi
    Nov 22, 2012 at 16:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.