【问题标题】:Wordpress how to get only parent posts for a custom post typeWordpress 如何仅获取自定义帖子类型的父帖子
【发布时间】:2021-12-15 16:26:09
【问题描述】:

在 wordpress 中仅显示自定义帖子类型存档页面的父帖子

我的代码:

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

结果:

“糟糕,没有帖子。”

【问题讨论】:

    标签: php wordpress wordpress-theming custom-post-type custom-wordpress-pages


    【解决方案1】:

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

    同时检查您在注册自定义帖子类型时是否将 '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

    【讨论】:

      【解决方案2】:

      post_parent 参数反过来起作用: 您需要此参数来查找所有父帖子:

      'post_parent' => 0,  // find parents  
      

      作为(相当笨重的)记忆辅助:父帖子为空/不存在。

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

      查询您当前帖子的所有子帖子。 父帖子具有此 ID

      看到这个帖子:
      How to query for posts (in hierarchical custom post type) that have children?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-04-27
        • 2013-10-28
        • 2014-10-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-27
        • 1970-01-01
        相关资源
        最近更新 更多