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

WordPress 6.1升级后自定义Meta Box字段无法保存URL的代码修复咨询

问题原因及修改方案

核心问题

  1. 代码中调用wp_kses时使用的$allowed变量未定义,WordPress 6.1对未定义参数的处理更严格,导致过滤规则异常,URL被错误过滤。
  2. 默认的wp_kses规则会对URL进行严格限制,若未明确允许URL格式的内容,会直接移除相关内容。

修改步骤

1. 修复内容过滤逻辑

在cd_meta_box_save函数内,先定义明确的允许内容规则,或改用更适配的安全处理函数:

方案一:定义支持URL的HTML规则(适用于带链接的描述内容)

add_action( 'save_post', 'cd_meta_box_save' );
function cd_meta_box_save( $post_id )
{
    // Bail if we're doing an auto save
    if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;

    // if our nonce isn't there, or we can't verify it, bail
    if( !isset( $_POST['meta_box_nonce'] ) || !wp_verify_nonce( $_POST['meta_box_nonce'], 'my_meta_box_nonce' ) ) return;

    // if our current user can't edit this post, bail
    if( !current_user_can( 'edit_post' ) ) return;

    // 定义允许的内容规则,支持链接、普通文本及基础格式标签
    $allowed = array(
        'a' => array(
            'href' => array(),
            'title' => array()
        ),
        'br' => array(),
        'em' => array(),
        'strong' => array()
    );

    // Make sure your data is set before trying to save it
    if( isset( $_POST['m_meta_description'] ) ) {
        update_post_meta( $post_id, 'm_meta_description', wp_kses( $_POST['m_meta_description'], $allowed ) );
    }    
}

方案二:仅处理纯文本+URL(适用于无HTML的描述内容)

add_action( 'save_post', 'cd_meta_box_save' );
function cd_meta_box_save( $post_id )
{
    // Bail if we're doing an auto save
    if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;

    // if our nonce isn't there, or we can't verify it, bail
    if( !isset( $_POST['meta_box_nonce'] ) || !wp_verify_nonce( $_POST['meta_box_nonce'], 'my_meta_box_nonce' ) ) return;

    // if our current user can't edit this post, bail
    if( !current_user_can( 'edit_post' ) ) return;

    // Make sure your data is set before trying to save it
    if( isset( $_POST['m_meta_description'] ) ) {
        // 用wp_kses_post处理,允许常规文本和URL,自动过滤危险内容
        $clean_content = wp_kses_post( $_POST['m_meta_description'] );
        update_post_meta( $post_id, 'm_meta_description', $clean_content );
    }    
}

2. 修复前端输出的安全问题

在add_to_wp_head函数中,添加安全转义避免XSS风险:

add_action('wp_head', 'add_to_wp_head');
function add_to_wp_head( )
{
    if (is_single())
    {
        global $post;
        $m_meta_description = get_post_meta($post->ID, 'm_meta_description', true);
        if ( !empty( $m_meta_description ) ) {
            echo '<meta name="description" content="' . esc_attr( $m_meta_description ) . '"/>';
        }
    }
}

额外说明

WordPress 6.1加强了内容过滤的严格性,未定义的$allowed参数会导致wp_kses使用最严格的默认规则,直接移除所有可能的“不安全”内容(包括URL),因此必须明确指定允许的内容规则,或使用适配的安全处理函数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 23:35:20