0

Ok I'm trying to display the parent and the child page links with their featured images

I have this code but the problem wis when on a childpage it doesn't show up how can i make it work?

<?php
$child_pages = $wpdb->get_results("SELECT *    FROM $wpdb->posts WHERE post_parent = ".$post->ID."    AND post_type = 'page' ORDER BY menu_order", 'OBJECT');
if ( $child_pages ) :
    foreach ( $child_pages as $pageChild ) : setup_postdata( $pageChild ); ?>
        <div class="child-thumb">
            <?php echo get_the_post_thumbnail($pageChild->ID, 'thumbnail'); ?>
            <a href="<?php echo  get_permalink($pageChild->ID); ?>" rel="bookmark" title="<?php echo $pageChild->post_title; ?>"><?php echo $pageChild->post_title; ?></a>
        </div>
    <?php endforeach;
endif; ?>
1
  • I meant that I want to be able to display the parent and child pages on both the parent and child not only on the parent page. also to display this only when there are childpages
    – Wito
    Commented Sep 16, 2013 at 17:03

1 Answer 1

1

You need only a bit of logic while setting the parent variable.

After that is better using the standard wordpress function get_pages instead of using a raw $wpdb query.

Then, once you use setup_postdata for the pages, you can use the standard template tags instad of echo the raw page object properties.

Finally after the loop on pages, we have to reset the post data using wp_reset_postdata, because we have altered the global $post variable by calling setup_postdata.

See inline comments for further explainations:

// if we are on a parent page set the $parent variable to current post id
// otherwise set $parent variable to current post parent
$parent = $post->post_parent == 0 ? $post->ID : $post->post_parent;

// if we use current post parent as $paren, exclude the current page
$exclude = $parent == $post->post_parent ? $post->ID : false;

// get all the children
$args = array( 'parent' => $parent, 'sort_column' => 'menu_order' );
if ( $exclude ) $args['exclude'] = $exclude;
$child_pages = get_pages($args);

// show only if there are children
if ( ! empty($child_pages) ) {
  global $post;
  foreach ( $child_pages as $post ) { setup_postdata( $post );
  ?>
  <div class="child-thumb">
    <?php the_post_thumbnail('thumbnail'); ?>
    <a href="<?php the_permalink(); ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a>
  </div>
  <?php
  }
  wp_reset_postdata();
}

Your Answer

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

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