Display only parent posts of a custom post type archive page in wordpress
My code :
$args = array(
'post_type' => 'programs',
'post_parent' => get_the_ID(),
);
$article_posts = new WP_Query($args);
if($article_posts->have_posts()) :
?>
<?php while($article_posts->have_posts()) : $article_posts->the_post();
$post_id = get_the_ID();
$post_link = get_permalink($post_id);
$post_title = get_the_title();
$featured_img_url = get_the_post_thumbnail_url(get_the_ID());
?>
<p> post </p>
<?php endwhile; ?>
<?php else: ?>
Oops, there are no posts.
<?php endif; ?>
<?php echo "</ul>";?>
Result:
"Oops, there are no posts."
2
Answers
According to the documentation if you only want the top level posts(i.e parents) then you would need to set the
post_parent
to0
not the id of the current page.Also check if you’ve set the
'hierarchical'
argument totrue
when you registered your custom post type.Also it’s a good idea to use
wp_reset_postdata
function after you’re done with your loop!So your code would be something like this:
WP_Query
Docspost_parent
argument works the other way round :You need this arg to find all parent posts:
As a (pretty clunky) memory aid: Parent post is Null /doesn’t exist.
Query all child posts of your current post. Parent post has this ID.
See this thread:
How to query for posts (in hierarchical custom post type) that have children?