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?
-
do you mean something like related posts– Pieter GoosenCommented Dec 22, 2014 at 4:25
-
yes quite similar except this is by post parent– RurikoCommented Dec 22, 2014 at 4:55
-
I'm a bit late :-), but the solution from @Roberthue should work. Good luck– Pieter GoosenCommented Dec 22, 2014 at 5:53
Add a comment
|
1 Answer
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.
-
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?– RurikoCommented 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. Commented Dec 22, 2014 at 9:23