[英]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在 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." “哎呀,没有帖子。”
According to the documentation if you only want the top level posts(ie parents) then you would need to set the post_parent
to 0
not the id of the current page. 根据文档,如果您只想要顶级帖子(即父母),那么您需要将post_parent
设置为0
而不是当前页面的 id。
Also check if you've set the 'hierarchical'
argument to true
when you registered your custom post type.还要检查您在注册自定义帖子类型时是否已将'hierarchical'
参数设置为true
。
Also it's a good idea to use wp_reset_postdata
function after you're done with your loop!在完成循环后使用wp_reset_postdata
函数也是一个好主意!
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();
post_parent
argument works the other way round : You need this arg to find all parent posts: post_parent
参数post_parent
:您需要此参数来查找所有父帖子:
'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 .父帖子具有此 ID 。
See this thread:看到这个线程:
How to query for posts (in hierarchical custom post type) that have children? 如何查询有孩子的帖子(分层自定义帖子类型)?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.