1

I have a custom post type with children posts. If I'm viewing one of the children post how can I list other children posts that uses the same parent?

3
  • do you mean something like related posts Commented Dec 22, 2014 at 4:25
  • yes quite similar except this is by post parent
    – Ruriko
    Commented Dec 22, 2014 at 4:55
  • I'm a bit late :-), but the solution from @Roberthue should work. Good luck Commented Dec 22, 2014 at 5:53

1 Answer 1

1

You can get the list of other posts with same post parent by running a custom query. You should supply parent post id in post_parent parameter to WP_Query and exclude current post from custom query.

So this will be the custom query.

$parentpost = wp_get_post_parent_id( $post->ID );

if ( $parentpost && $parentpost != '0' ) {

    $currentpost = array( $post->ID );

    $args = array(
        'post_type' => 'cpt-name',
        'post_parent' => $parentpost,
        'post__not_in' => $currentpost,
        'ignore_sticky_posts' => 1,
        'paged' => $paged,
    );

    $my_query = new WP_Query( $args );

    if ( $my_query->have_posts() ) :

        while ( $my_query->have_posts() ) : $my_query->the_post();
            the_title();
        endwhile;

    endif;

    wp_reset_postdata();

} else {

    echo "Do something else.";

}

Oh and also, you will have to add your custom post type name in above code to work. I added cpt-name right now as an example. I hope this helps.

2
  • The code works except when I view the parent post it lists other parent posts which I don't want. How can I make if it's a parent post do something else?
    – Ruriko
    Commented Dec 22, 2014 at 8:26
  • You can always add a check, to do/show something else if user is on parent post. I have updated the answer, use updated code.
    – Robert hue
    Commented Dec 22, 2014 at 9:23

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.