【问题标题】:Wordpress Illegal string offsetWordpress 非法字符串偏移
【发布时间】:2017-02-21 13:09:49
【问题描述】:

我正在使用以下代码来确定复选框是否已被勾选,然后显示一些文本(如果有/没有作为测试)。

选中后,它可以正常工作并显示文本。

当它未选中时,我会在输入框行中收到以下消息,并在下面的代码中添加注释。

非法字符串偏移 'check_checkbox_field_0'

<?php

    function webdev_init() {
    ?>
        <h1>Title</h1>
        <h2>WedDev Overlay Plugin Options</h2>
        <form action='options.php' method='post'>
        <h2>Checking</h2>

        <?php
        settings_fields( 'my_option' );
        do_settings_sections( 'checking' );
        submit_button();
        ?>

        </form>
    <?php
    }

    function chec_settings_init() {

        register_setting( 'my_option', 'chec_settings' );

        add_settings_section(
            'chec_checking_section',
            __( 'Your section description', 'wp' ),
            'chec_settings_section_callback',
            'checking'
        );

        add_settings_field(
            'chec_checkbox_field_0',
            __( 'Settings field description', 'wp' ),
            'chec_checkbox_field_0_render',
            'checking',
            'chec_checking_section'
        );
    }

    function chec_settings_section_callback() {

        echo __( 'This section description', 'wp' );

    }

    function chec_checkbox_field_0_render() {

        $options = get_option( 'chec_settings' );
    ?>

    //Error message on line bellow
    <input type='checkbox' name='chec_settings[chec_checkbox_field_0]' value='1' <?php if ( 1 == $options['chec_checkbox_field_0'] ) echo 'checked="checked"'; ?> />

    <?php
    }

 $options = get_option( 'chec_settings' );
if ( is_array( $options ) && $options['chec_checkbox_field_0'] == '1' ) {
    echo 'Checked';
} else {
    echo 'Unchecked';
}

【问题讨论】:

    标签: php wordpress input


    【解决方案1】:

    这意味着给定的索引不在数组$options中。

    您似乎正在从 HTTP 请求中获取 $options 的值。由于您的输入是一个复选框,因此未选中时它不会出现在请求中。

    因为,在 html 表单的情况下,如果未选中复选框,则提交后请求中根本不存在复选框。

    这意味着复选框只有设置或未设置两种状态。因此,您应该检查isset() 以确定复选框是否被选中。

    if ( isset( $options['chec_checkbox_field_0'] ) && $options['chec_checkbox_field_0'] == '1' ) {
        echo 'Checked';
    } else {
        echo 'Unchecked';
    }
    

    【讨论】:

    • 好的。我在哪里检查 isset()?
    • 我添加了。请检查。
    • 这两处都换了吗?
    • 这两个地方是什么意思?
    • 您已经检查了给定代码中两个位置的条件。一个在您的评论下方,另一个在代码底部
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多