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

WordPress:Elementor编辑器中短码显示位置异常问题排查

Elementor短码编辑器渲染位置异常修复

问题原因

WordPress短码的核心规范是返回内容而非直接输出(echo)。你当前的代码使用echo直接输出HTML,在Elementor编辑器的渲染环境中,echo的内容会被提前写入页面缓冲区,导致内容出现在编辑器左上角;而前端页面因为缓冲区处理逻辑不同,所以显示正常。

修复方案

将所有echo操作改为字符串拼接,最终统一返回拼接好的HTML内容,递归函数也需要返回子内容而非直接输出。

修改后的完整代码

add_shortcode('mysubcategory', 'display_parent_subcategory');

function display_parent_subcategory($atts) {
    $atts = shortcode_atts(array(
        'category_slug' => '',
    ), $atts, 'show_parent');

    $category_slug = sanitize_text_field($atts['category_slug']);
    $output = '';
        
    // 获取指定的父分类
    $parent_category = get_term_by('slug', $category_slug, 'product_cat');

    if (isset($parent_category) && !is_wp_error($parent_category)) {
        $output .= '<ul class="menu_subcategory">';
        $output .= display_child_categories_recursive($parent_category->term_id);
        $output .= '</ul>';
    } else {
        $output .= '无效的分类别名';
    }
    
    return $output;
}

function display_child_categories_recursive($parent_category_id) {
    $child_output = '';
    // 获取当前分类的所有子分类,包含空分类
    $child_categories = get_terms(array(
        'taxonomy' => 'product_cat',
        'parent' => $parent_category_id,
        'hide_empty' => false,
    ));

    foreach ($child_categories as $child_category) {
        $child_output .= '<li class="cat_id_' . $child_category->term_id . '">
              <a href="' . get_term_link($child_category->term_id) . '">'
            . $child_category->name . '</a>';

        // 递归调用函数处理子分类
        $child_output .= '<ul>';
        $child_output .= display_child_categories_recursive($child_category->term_id);
        $child_output .= '</ul>';
        $child_output .= '</li>';
    }
    
    return $child_output;
}

关键修改说明

  1. 主函数新增$output变量,所有HTML内容通过.=拼接,最后返回该变量
  2. 递归函数新增$child_output变量,拼接子分类HTML后返回,主函数中接收并拼接该返回值
  3. 将代码中的HTML实体(&lt;、&quot;)替换为正常的HTML标签,提升代码可读性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 05:35:01