Wordpress 如何仅获取自定义 post 类型的父 posts

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

仅显示 wordpress 中自定义 post 类型存档页面的父 posts

我的代码:

$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>";?>

结果:

"Oops, there are no posts."

According to the documentation 如果您只想要顶级 posts(即 parents),那么您需要将 post_parent 设置为 0 而不是当前页面的id。

同时检查您是否在注册自定义 post 类型时将 'hierarchical' 参数设置为 true

此外,在完成循环后使用 wp_reset_postdata 函数也是个好主意!

所以你的代码应该是这样的:

$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

post_parent 参数反之亦然: 你需要这个参数来找到所有 parent posts:

'post_parent' => 0,  // find parents  

作为(相当笨重的)记忆辅助工具:Parent post is Null /doesn't exist.

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

查询您当前 post 的所有 child post。 Parent post 有这个 ID.

查看此线程:
How to query for posts (in hierarchical custom post type) that have children?