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

WP插件后台复选框提交后未保持勾选及单选复选框实现求助

WordPress插件单选选项实现(保存+勾选状态保持)

问题根源

你现在用复选框做单选需求本身就不对,复选框支持多选,而且原代码没给控件加选中状态判断,所以提交后没法保持勾选。换成单选按钮组就能解决互斥选择问题,再配合WordPress内置函数处理选中状态,就能实现需求。

完整解决方案代码

1. 注册设置(含安全校验)

function vsuc_register_settings() {
    // 注册设置,指定选项组、选项名,添加安全校验和默认值
    register_setting('vsuc_option_group', 'vsuc_style_choice', array(
        'sanitize_callback' => 'vsuc_sanitize_style_choice',
        'default' => 'style1' // 首次加载默认选中样式1
    ));
}
add_action('admin_init', 'vsuc_register_settings');

// 校验提交的值,确保只能是允许的选项
function vsuc_sanitize_style_choice($input) {
    $allowed = array('style1', 'style2');
    return in_array($input, $allowed) ? $input : 'style1';
}

2. 后台设置面板表单

把原来的复选框换成单选按钮组,用WordPress的checked()函数自动判断选中状态:

function vsuc_settings_page() {
    $selected = get_option('vsuc_style_choice', 'style1');
    ?>
    <div class="wrap">
        <h1>VSUC 插件设置</h1>
        <form method="post" action="options.php">
            <?php settings_fields('vsuc_option_group'); ?>
            <h3>样式选择</h3>
            <p>
                <label>
                    <input type="radio" name="vsuc_style_choice" value="style1" <?php checked($selected, 'style1'); ?>>
                    启用样式1
                </label>
            </p>
            <p>
                <label>
                    <input type="radio" name="vsuc_style_choice" value="style2" <?php checked($selected, 'style2'); ?>>
                    启用样式2
                </label>
            </p>
            <?php submit_button(); ?>
        </form>
    </div>
    <?php
}

3. 前端样式输出逻辑

根据保存的选项输出对应样式:

$selected_style = get_option('vsuc_style_choice', 'style1');
if ($selected_style === 'style1') {
    echo '<style>/* 这里写样式1的CSS代码 */</style>';
} elseif ($selected_style === 'style2') {
    echo '<style>/* 这里写样式2的CSS代码 */</style>';
}

关键说明

  • 单选按钮必须共用同一个name属性(这里是vsuc_style_choice),浏览器会自动处理互斥选择,只能选一个。
  • checked()是WordPress内置工具函数,对比当前保存的选项和单选按钮的value,匹配的话自动输出checked="checked",实现提交后保持勾选状态。
  • 添加sanitize_callback是为了安全过滤,防止恶意提交非法值,确保保存的只能是你预设的style1或style2。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 00:27:37