Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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!

share|improve this question
add comment

3 Answers 3

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

share|improve this answer
    
Could you show the full code? Thanks! –  nicolas Nov 22 '12 at 14:01
    
Hi @nicolas, filled in the full code for you. –  fischi Nov 22 '12 at 16:17
add comment

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.

share|improve this answer
add comment
up vote 0 down vote accepted

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; ?>
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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