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

如何解决Shortcode调用插件中FAQ自定义文章类型数据的循环问题?

问题分析与解决方案

核心问题1:短码名称不匹配

你注册短码时用的是customshortcode,但在页面里调用的是[displayFaqs],WordPress找不到对应的短码处理函数,所以直接把短码文本原样输出了。

核心问题2:变量未初始化+无实际数据查询

displayFaqs函数里的$html没有提前声明初始化,直接用.=会触发PHP警告;而且当前函数只返回固定文本,根本没去查询你创建的faqs自定义文章类型数据。


修正后的完整代码

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',
                'parent' => 'Parent Faq'
            ),
            'public' => true,
            'menu_position' => 15,
            'supports' => array( 'title', 'editor', 'comments', 'thumbnail', 'custom-fields' ),
            'taxonomies' => array( '' ),
            'menu_icon' => 'dashicons-editor-help',
            'has_archive' => true
        )
    );
}

2. 修正后的短码与展示函数

function displayFaqs() {
    // 初始化HTML变量
    $html = '';
    
    // 查询faqs自定义文章类型的公开内容
    $faq_query = new WP_Query(array(
        'post_type' => 'faqs',
        'post_status' => 'publish',
        'posts_per_page' => -1, // 显示所有FAQ
        'orderby' => 'title',
        'order' => 'ASC'
    ));

    // 如果有查询结果,循环输出
    if ($faq_query->have_posts()) {
        $html .= '<div class="faq-container">';
        while ($faq_query->have_posts()) {
            $faq_query->the_post();
            $html .= '<div class="faq-item">';
            $html .= '<h3 class="faq-title">' . get_the_title() . '</h3>';
            $html .= '<div class="faq-content">' . get_the_content() . '</div>';
            $html .= '</div>';
        }
        $html .= '</div>';
        // 重置查询,避免干扰全局循环
        wp_reset_postdata();
    } else {
        $html .= '<p>No FAQs found.</p>';
    }

    return $html;
}
// 注册与调用名称一致的短码
add_shortcode('displayFaqs','displayFaqs');

额外注意点

如果之后仍出现短码重复显示的情况,检查函数里是否调用了the_content()——这个函数会自动触发短码解析,可能导致WordPress递归解析当前短码,进而重复输出。当前代码用get_the_content()(不会自动解析短码)就没问题,如果需要解析FAQ内容里的短码,可以替换为apply_filters('the_content', get_the_content())。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 12:55:18