Home > Blockchain >  Wordpress how to get only parent posts for a custom post type
Wordpress how to get only parent posts for a custom post type

Time:11-01

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

CodePudding user response:

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

CodePudding user response:

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?

  • Related