You need to enable JavaScript to run this app. WordPress 受保护代码防护:AJAX提交密码免页面刷新的实现方案咨询
优惠活动
大模型
产品
解决方案
定价
更多

WordPress 受保护代码防护:AJAX提交密码免页面刷新的实现方案咨询

WordPress Prism代码块访问控制可落地实现

核心匹配逻辑:文章内Prism代码块转受保护短代码

通过挂载the_content过滤器,在内容输出前用正则匹配所有Prism渲染的目标代码块,覆盖pre/code标签上的所有类名变体(含类顺序调整、附加自定义类的场景),替换为自定义防护短代码:

add_filter('the_content', 'wp_protect_prism_code_blocks', 20);
function wp_protect_prism_code_blocks($content) {
    // 正则匹配规则:支持pre/code标签任意位置的语言类、任意类名顺序
    $pattern = '/<pre[^>]*>.*?<code[^>]*class="[^"]*(?<lang>language-php|lang-php|language-html|lang-html|language-css|lang-css|language-js|lang-js)[^"]*"[^>]*>(?<code_content>.*?)<\/code><\/pre>/is';
    // 匹配结果替换为防护短代码,携带匹配到的语言类参数
    $replacement = '[protected_code lang="${lang}"]${code_content}[/protected_code]';
    return preg_replace($pattern, $replacement, $content);
}

防护短代码核心逻辑

实现Cookie校验、提示占位、密码表单输出全流程:

  • 校验用户Cookie中的验证值,匹配成功直接渲染受保护代码块
  • 验证失败时输出空提示占位div+密码提交表单
  • 通过本地化脚本把AJAX配置传给前端JS
add_shortcode('protected_code', 'render_protected_code_block');
function render_protected_code_block($atts, $content = null) {
    // 短代码接收语言类参数
    $atts = shortcode_atts(array(
        'lang' => 'language-php'
    ), $atts);

    // 从站点配置读取预设的访问密码(建议存在站点设置项,不硬编码)
    $access_pwd = get_option('prism_protect_access_pwd');
    $valid_auth_hash = md5( wp_salt('auth') . $access_pwd );

    // Cookie存在有效校验值,直接输出代码块
    if (isset($_COOKIE['prism_code_auth']) && $_COOKIE['prism_code_auth'] === $valid_auth_hash) {
        return '<pre><code class="'.esc_attr($atts['lang']).'">' . esc_textarea($content) . '</code></pre>';
    }

    // 验证失败场景:输出空提示区+密码表单
    $output = '
    <div class="protected-code-wrap">
        <div id="code-protect-notice" class="protect-notice"></div>
        <form id="code-protect-form">
            <input type="password" name="protect_pwd" placeholder="请输入访问密码" required>
            <button type="submit">确认访问</button>
        </form>
    </div>';

    // 挂载前端脚本并传参
    wp_enqueue_script('protect-code-js', get_stylesheet_directory_uri().'/assets/protect-code.js', array('jquery'), '1.0', true);
    wp_localize_script('protect-code-js', 'protectCodeConfig', array(
        'ajaxUrl' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('protect_code_nonce'),
        'wrapContent' => $content,
        'codeLang' => $atts['lang']
    ));

    return $output;
}

可正常运行的AJAX实现

之前AJAX失效的核心原因基本都是漏注册了未登录用户的AJAX钩子、硬写请求地址、未加nonce校验

// 必须同时注册两个钩子:已登录用户、未登录访客的AJAX请求入口
add_action('wp_ajax_verify_protect_pwd', 'handle_protect_pwd_verify');
add_action('wp_ajax_nopriv_verify_protect_pwd', 'handle_protect_pwd_verify');
function handle_protect_pwd_verify() {
    // 校验请求合法性
    check_ajax_referer('protect_code_nonce', 'nonce');
    $input_pwd = sanitize_text_field($_POST['input_pwd']);
    $access_pwd = get_option('prism_protect_access_pwd');
    $valid_auth_hash = md5( wp_salt('auth') . $access_pwd );

    // 密码校验通过
    if ($input_pwd === $access_pwd) {
        // 设置7天有效期的HttpOnly Cookie
        setcookie(
            'prism_code_auth',
            $valid_auth_hash,
            time() + 7 * DAY_IN_SECONDS,
            COOKIEPATH,
            COOKIE_DOMAIN,
            is_ssl(),
            true
        );
        wp_send_json_success([
            'renderContent' => '<pre><code class="'.esc_attr($_POST['code_lang']).'">' . esc_textarea($_POST['protected_content']) . '</code></pre>'
        ]);
    }

    // 密码校验失败
    wp_send_json_error([
        'message' => '密码错误,请重新输入'
    ]);
}

前端JS实现(对应脚本文件内容)

jQuery(document).ready(function($) {
    $('#code-protect-form').on('submit', function(e) {
        // 阻止表单默认提交导致的页面刷新
        e.preventDefault();
        const inputPwd = $(this).find('input[name="protect_pwd"]').val();
        const noticeBox = $('#code-protect-notice');

        $.post(protectCodeConfig.ajaxUrl, {
            action: 'verify_protect_pwd',
            nonce: protectCodeConfig.nonce,
            input_pwd: inputPwd,
            protected_content: protectCodeConfig.wrapContent,
            code_lang: protectCodeConfig.codeLang
        }).done(function(res) {
            if (res.success) {
                // 验证通过:替换容器内容为受保护代码块
                $('.protected-code-wrap').html(res.data.renderContent);
                // 触发Prism重新高亮动态插入的代码块
                if (window.Prism) Prism.highlightAll();
            } else {
                // 验证失败:在占位区展示错误提示
                noticeBox.text(res.data.message).css('color', '#dc3545');
            }
        }).fail(function() {
            noticeBox.text('请求异常,请稍后重试').css('color', '#dc3545');
        });
    });
});

常见失效点排查

  • 正则匹配漏判:确保能识别Prism将语言类放在pre标签而非code标签的场景,覆盖自定义类与语言类混合的情况
  • AJAX钩子缺失:未注册wp_ajax_nopriv_verify_protect_pwd钩子会导致访客请求时无响应
  • 动态渲染未触发高亮:AJAX插入的代码块需要手动调用Prism.highlightAll()才能正常高亮
  • Cookie设置异常:未开启HttpOnly标记、未指定站点路径会导致cookie不生效,用户反复被要求输入密码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.31 00:45:03