You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WordPress中循环自定义文章类型faq的分类及对应文章?

WordPress 自定义文章类型FAQ按分类展示(仅显示含文章的分类)

你的核心问题是没有将当前循环的分类与FAQ文章关联,导致每次获取的是所有FAQ文章,无法对应到具体分类。以下是修改后的完整代码,实现仅展示包含FAQ文章的分类及下属文章:

$category_args = array(
    'orderby' => 'name',
    'order' => "ASC",
    // 若使用默认分类,保持默认;若为自定义分类法,需添加'taxonomy' => '你的分类法slug'
);
$categories = get_categories( $category_args );

foreach ( $categories as $category ) {

    $post_args = array(
        'post_type' => 'faq',
        'post_status' => 'publish',
        'numberposts' => -1,
        'orderby' => 'title',
        'order' => 'ASC',
        // 关联当前分类(默认分类用此参数)
        'category' => $category->term_id,
        // 如果是自定义分类法,替换上面的category参数为以下代码
        /*
        'tax_query' => array(
            array(
                'taxonomy' => 'faq_category', // 替换为你的自定义分类法slug
                'field'    => 'term_id',
                'terms'    => $category->term_id,
            ),
        ),
        */
    );

    $posts = get_posts( $post_args );

    // 仅当分类下有FAQ文章时才输出
    if ( ! empty( $posts ) ) {
        // 输出分类标题
        echo '<h3>' . esc_html( $category->name ) . '</h3>';
        // 输出文章列表
        echo '<ul>';
        foreach ( $posts as $post ) {
            setup_postdata( $post );
            echo '<li><a href="' . get_permalink( $post->ID ) . '">' . esc_html( get_the_title() ) . '</a></li>';
        }
        echo '</ul>';
        wp_reset_postdata(); // 重置全局文章数据,避免冲突
    }
}

关键修改说明:

  1. 关联分类与文章:在$post_args中添加分类参数,确保只获取当前分类下的FAQ文章。若使用自定义分类法,需改用tax_query替代默认的category参数。
  2. 判断文章存在性:通过! empty( $posts )过滤掉没有FAQ文章的分类,避免空分类显示。
  3. 安全与规范:使用esc_html()转义输出内容,防止XSS攻击;用setup_postdata()和wp_reset_postdata()处理文章数据,避免全局变量污染。

内容的提问来源于stack exchange,提问作者Sackadelic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 13:42:45