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

如何通过WP KSES过滤器允许嵌套在noscript中的iframe标签?

解决WP KSES过滤时noscript嵌套iframe被转义的问题

问题场景

使用Advanced Custom Fields(ACF)时,通过wp_kses_allowed_html过滤器已经成功允许了iframe、script、style、noscript标签,但嵌套在noscript内的iframe会被WP KSES转为带引号的文本。尝试过在noscript的允许规则中直接添加iframe为true,或者完整定义iframe属性,都未生效。

原代码如下:

function allow_iframe_script_tags( $allowedposttags ) {
    $allowedposttags['script'] = array(
        'type' => true,
        'src' => true,
    );

    $allowedposttags['noscript'] = array();

    // Also allow iframe directly
    $allowedposttags['iframe'] = array(
        'src' => true,
        'height' => true,
        'width' => true,
    );

    $allowedposttags['style'] = array();

    return $allowedposttags;
}

add_filter( 'wp_kses_allowed_html', 'allow_iframe_script_tags', 10, 1 );

解决方案

修正过滤器函数,正确接收上下文参数,并规范嵌套标签的允许规则:

function allow_iframe_script_tags( $allowedposttags, $context ) {
    // 针对需要的上下文添加规则(比如文章内容、自定义字段,可根据实际场景调整)
    if ( in_array( $context, array( 'post', 'custom' ) ) ) {
        // 允许script标签及属性
        $allowedposttags['script'] = array(
            'type' => true,
            'src' => true,
        );

        // 允许noscript标签,并声明其可包含的iframe子标签及属性
        $allowedposttags['noscript'] = array();
        $allowedposttags['noscript']['iframe'] = array(
            'src' => true,
            'height' => true,
            'width' => true,
        );

        // 直接允许独立的iframe标签
        $allowedposttags['iframe'] = array(
            'src' => true,
            'height' => true,
            'width' => true,
        );

        // 允许style标签
        $allowedposttags['style'] = array();
    }

    return $allowedposttags;
}
// 注意这里要指定接收2个参数,第三个参数设为2
add_filter( 'wp_kses_allowed_html', 'allow_iframe_script_tags', 10, 2 );

关键说明

  • 接收上下文参数:wp_kses_allowed_html过滤器默认会传递2个参数,之前的函数只接收了1个,导致在ACF字段等特定上下文下规则未被正确应用。通过判断$context,可以精准控制规则生效的场景。
  • 嵌套标签规则规范:WP KSES对嵌套标签的允许逻辑要求,必须在父标签的规则数组内,完整定义子标签的允许属性,不能仅设置为true。需要保证noscript下的iframe属性规则和独立iframe的规则一致。
  • 缓存与测试:修改代码后,清空WordPress缓存,重新保存包含嵌套内容的ACF字段,再查看前端输出是否正常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 21:37:45