• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

258
Views
Wordpress how to get only parent posts for a custom post type

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."

about 3 years ago · Santiago Trujillo
2 answers
Answer question

0

According to the documentation if you only want the top level posts(i.e parents) then you would need to set the post_parent to 0 not the id of the current page.

Also check if you've set the 'hierarchical' argument to true 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:

$args = array(
  'post_type'   => 'programs',
  'post_parent' => 0,
);

$article_posts = new WP_Query($args);

echo echo "</ul>";
if($article_posts->have_posts()) : 
  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><?php echo $post_title; ?></p>
  <?php 
  endwhile; 
  ?>
<?php 
else:  
?>
Oops, there are no posts.
<?php  
endif;
?>    
<?php echo "</ul>";

wp_reset_postdata();

WP_QueryDocs

about 3 years ago · Santiago Trujillo Report

0

post_parent argument works the other way round : You need this arg to find all parent posts:

'post_parent' => 0,  // find parents  

As a (pretty clunky) memory aid: Parent post is Null /doesn't exist.

'post_parent' => get_the_ID()  //find children   

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?

about 3 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error