如何在单篇文章页(single.php)展示同分类FAQ自定义文章
WordPress单篇文章页同分类FAQ展示代码修正方案
原代码核心问题
- 误用
the_category()直接输出分类,而非获取可用于逻辑判断的分类数据对象 - 未正确定义主文章的分类变量,导致后续匹配逻辑失效
- FAQ采用全量查询后再判断的方式,效率低下
- 自定义文章类型注册时分类关联写法不规范
- 多处变量调用逻辑错误(如对字符串进行对象属性调用)
修正后的代码实现
1. 优化自定义文章类型注册代码
将分类关联直接整合到注册参数中,替代单独的关联函数,写法更规范:
add_action( 'init', 'create_faqs' ); function create_faqs() { register_post_type( 'faqs', array( 'labels' => array( 'name' => 'FAQs', 'singular_name' => 'FAQ', 'add_new' => 'Add New', 'add_new_item' => 'Add New Faq', 'edit' => 'Edit', 'edit_item' => 'Edit Faq', 'new_item' => 'New Faq', 'view' => 'View', 'view_item' => 'View Faq', 'search_items' => 'Search FAQs', 'not_found' => 'No FAQs found', 'not_found_in_trash' => 'No faqs found in Trash' ), 'public' => true, 'menu_position' => 15, 'menu_icon' => 'dashicons-editor-help', 'supports' => array( 'title', 'editor', 'comments', 'thumbnail', 'custom-fields' ), 'taxonomies' => array( 'category' ), // 直接关联默认分类法 'has_archive' => true ) ); }
2. 修正single.php中的FAQ展示逻辑
通过get_the_category()获取主文章分类ID,直接在查询中筛选同分类FAQ,避免冗余判断:
<?php while (have_posts()): the_post(); ?> <h1 class="page-title"><?php the_title(); ?></h1> <p><?php the_content(); ?></p> <?php get_template_part("widgets/cta"); ?> <?php // 获取当前文章的所有分类ID $current_categories = get_the_category(); $cat_ids = array(); foreach ($current_categories as $category) { $cat_ids[] = $category->term_id; } // 查询与当前文章共享至少一个分类的FAQ $args_faq = array( "post_type" => "faqs", "posts_per_page" => 2, "post__not_in" => array(get_the_ID()), // 排除当前文章(若当前文章为FAQ类型) "tax_query" => array( array( "taxonomy" => "category", "field" => "term_id", "terms" => $cat_ids, "operator" => "IN" ) ) ); $faq_loop = new WP_Query($args_faq); if ($faq_loop->have_posts()) : echo '<div class="related-faqs"><h3>相关FAQ</h3>'; while ($faq_loop->have_posts()) : $faq_loop->the_post(); ?> <div class="faq-item"> <h4><?php the_title(); ?></h4> <div class="faq-content"><?php the_content(); ?></div> </div> <?php endwhile; echo '</div>'; endif; // 重置查询上下文,避免影响后续模板函数 wp_reset_postdata(); ?> <?php endwhile; ?>
关键修正说明
- 用
get_the_category()替代the_category():前者返回分类对象数组用于逻辑处理,后者仅用于直接输出分类链接 - 通过
tax_query在WP_Query中直接筛选同分类FAQ:减少数据库查询次数,提升页面加载效率 - 添加
wp_reset_postdata():重置查询上下文,防止后续模板函数调用出错 - 删除原代码中无效的变量错误调用,简化匹配逻辑
内容的提问来源于stack exchange,提问作者Roberto Nevilis
相关产品推荐
相关产品推荐

