WordPress自定义文章类型如何仅查询并显示父级文章
问题修复方案
核心错误点
- 原代码
post_parent参数赋值错误:你传入的get_the_ID()是查询当前页面的子级文章,和你要查「无父级的顶层父文章」需求完全相反,顶层文章的post_parent固定值为0
调整后可用代码
// 仅查询programs类型的顶层父文章 $args = array( 'post_type' => 'programs', 'post_parent' => 0, 'posts_per_page' => -1, // 可按需调整展示数量,-1为全部展示 'post_status' => 'publish' // 仅查询已发布的文章 ); $article_posts = new WP_Query($args); if($article_posts->have_posts()) : ?> <ul> <!-- 补全原代码缺失的ul起始标签,匹配末尾的闭合标签 --> <?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($post_id); ?> <li> <!-- 可按需调整输出结构,以下为示例 --> <a href="<?php echo esc_url($post_link); ?>"> <?php if($featured_img_url): ?> <img src="<?php echo esc_url($featured_img_url); ?>" alt="<?php echo esc_attr($post_title); ?>"> <?php endif; ?> <p><?php echo esc_html($post_title); ?></p> </a> </li> <?php endwhile; ?> </ul> <?php else: ?> <p>Oops, there are no posts.</p> <?php endif; // 重置文章数据,避免影响页面后续的查询逻辑 wp_reset_postdata(); ?>
优化建议
如果是自定义文章类型的专属存档页(即archive-programs.php模板),更推荐用pre_get_posts钩子修改主查询实现需求,无需额外创建自定义查询,性能更好:
// 把这段代码放到主题的functions.php文件中 add_action('pre_get_posts', function($query) { // 仅在前台programs存档页的主查询生效 if (!is_admin() && $query->is_main_query() && is_post_type_archive('programs')) { $query->set('post_parent', 0); } });
添加上述钩子后直接用存档页默认的主循环即可输出内容,不需要自定义WP_Query。
内容的提问来源于stack exchange,提问作者Rama Absa
相关产品推荐
相关产品推荐

