WordPress自定义分类管理面板中如何显示该分类下所有关联文章列表?
修复WordPress自定义分类(Vendors)编辑面板关联文章列表的问题
我帮你排查了下代码里的问题,核心原因是你用了默认文章分类的cat参数来查询,但vendors是自定义分类法,这个参数不生效,导致查询不到关联的文章。另外原代码里还有一些冗余的代码(比如没用到的$cat_meta变量),下面是修正后的完整代码:
// 在Vendors分类编辑面板添加关联文章列表 add_action('admin_init', 'vendors_custom_fields', 1); function vendors_custom_fields() { add_action('vendors_edit_form_fields', 'category_custom_fields_form'); } function category_custom_fields_form($tag) { $term_id = $tag->term_id; // 自定义分类查询需要用tax_query指定分类法 $args = array( 'post_type' => 'post', // 如果是自定义文章类型,替换成你的类型名称,比如'product' 'posts_per_page' => -1, // 显示所有关联文章,去掉的话默认显示10篇 'tax_query' => array( array( 'taxonomy' => 'vendors', // 指定自定义分类法 'field' => 'term_id', 'terms' => $term_id, ), ), ); $query = new WP_Query($args); ?> <tr class="form-field"> <th scope="row">关联的文章列表:</th> <td> <?php if ($query->have_posts()) : ?> <ul> <?php while ($query->have_posts()) : $query->the_post(); ?> <li><a href="<?php echo get_edit_post_link(); ?>" target="_blank"><?php echo get_the_title(); ?></a></li> <?php endwhile; ?> </ul> <?php wp_reset_postdata(); ?> <?php else : ?> <p><?php esc_html_e('该分类下暂无关联文章'); ?></p> <?php endif; ?> </td> </tr> <?php }
关键修改点说明:
- 替换了WP_Query的参数:用
tax_query替代cat,明确指定自定义分类法vendors和对应的分类ID,这样才能正确查询到关联的文章 - 添加了
posts_per_page => -1:确保显示该分类下的所有文章,默认WP_Query只显示10篇 - 把文章标题改成可点击的编辑链接:方便直接跳转到文章编辑页面,提升操作效率
- 移除了冗余的
$cat_meta变量:原代码里这个变量没有实际用途,所以删掉了
如果你的关联文章是自定义文章类型(比如product),记得把post_type的值改成对应的类型名称。
内容的提问来源于stack exchange,提问作者BlackStar1991
相关产品推荐
相关产品推荐

