在WordPress archive.php中显示ACF分类关联自定义文章链接问题
解决方案
问题根源在于WordPress默认的分类归档查询仅包含post类型,自定义文章类型不会被自动纳入,因此需要调整查询逻辑来覆盖所有关联目标分类法的文章类型。以下提供两种可行方案:
方案一:修改主查询(推荐,复用现有归档循环)
在主题的functions.php中添加以下代码,自动将所有关联当前分类法的自定义文章类型纳入主查询范围:
function include_custom_post_types_in_taxonomy_archives( $query ) { // 仅对前台分类归档的主查询生效 if ( ! is_admin() && $query->is_main_query() && $query->is_tax() ) { // 获取当前分类法对象 $taxonomy = get_queried_object()->taxonomy; // 自动获取所有关联该分类法的公开自定义文章类型 $custom_post_types = get_post_types( array( 'public' => true, '_builtin' => false, 'taxonomies' => array( $taxonomy ) ) ); // 可选:加入默认post类型(如果需要包含普通文章) $custom_post_types[] = 'post'; // 更新查询的文章类型参数 $query->set( 'post_type', $custom_post_types ); } } add_action( 'pre_get_posts', 'include_custom_post_types_in_taxonomy_archives' );
添加后,archive.php中原有的主循环(have_posts()/the_post())会自动输出所有关联当前分类的自定义文章内容,无需修改归档页模板代码。
方案二:自定义WP_Query(独立渲染内容)
如果不想修改主查询,可在archive.php需要显示内容的位置,直接创建自定义查询并输出文章链接:
// 获取当前分类术语对象 $current_term = get_queried_object(); // 自定义查询参数 $args = array( 'post_type' => array( 'main_wall', 'short_wall', 'post' ), // 替换为你的自定义文章类型slug 'posts_per_page' => -1, // 显示全部内容,可改为具体数字(如10) 'tax_query' => array( array( 'taxonomy' => $current_term->taxonomy, 'field' => 'term_id', 'terms' => $current_term->term_id, ), ), ); $custom_query = new WP_Query( $args ); // 循环输出文章链接 if ( $custom_query->have_posts() ) : echo '<div class="custom-post-links">'; while ( $custom_query->have_posts() ) : $custom_query->the_post(); echo '<a href="' . get_permalink() . '" class="post-link">' . get_the_title() . '</a>'; endwhile; echo '</div>'; wp_reset_postdata(); // 重置查询对象,避免影响后续内容 endif;
注意事项
- 确认自定义文章类型注册时,已通过
taxonomies参数关联目标分类法,示例代码如下:
register_post_type( 'main_wall', array( // 其他注册参数... 'taxonomies' => array( 'your_taxonomy_slug' ), // 替换为你的分类法slug ) );
内容的提问来源于stack exchange,提问作者alib0ng0
相关产品推荐
相关产品推荐

