1

I have created a WordPress plugin and added an options page.

There is an error message when the check box unchecked:

Notice: Undefined index: upo_enable

But when the check box checked it works good. See the GIF below:

my plugin's options page

The Demo Code:

<?php
/*
Plugin Name: update option
Plugin URI: 
Description: Plugin Demo.
Author: Ryan
Version: 1.0
Author URI: 
*/

if ( !function_exists('upo_admin_page') ) :
function upo_admin_page() {
    add_options_page( 
        __( 'Update Option', 'demo' ),
        __( 'Update Option', 'demo' ),
        'manage_options',
        'update-option',
        'upo_option_page'
    );
}
endif;
add_action( 'admin_menu', 'upo_admin_page' );

// Update Options.
if ( !function_exists('upo_options_update') ) :
function upo_options_update() {
    $updated = '<div class="updated settings-error notice is-dismissible"><p><strong>' . __('Settings saved.', 'demo') . '</strong></p></div>'; 
    if (isset($_POST['update_options'])) {
        update_option('upo_enable', $_POST['upo_enable']);
        echo $updated;
    }
}
endif;

if ( !function_exists('upo_option_page') ) :
function upo_option_page() {

?>
<div class="upo-wrap">
    <h2><?php _e('Update Options') ?></h2>
    <?php upo_options_update(); ?>
    <div class="update-option">
        <form method="post" action="<?php echo admin_url( 'options-general.php?page=update-option' ); ?>">
        <?php wp_nonce_field('update_options');?>
        <table class="upo-options-form">
            <tr valign="top">
                <th scope="row"><?php _e('Enable'); ?></th>
                <td><label for="upo_enable">
                <input name="upo_enable" type="checkbox" id="upo_enable" value="true" <?php checked('true', get_option('upo_enable')); ?> /><?php _e('Test Text'); ?></label>
                </td>
            </tr>
        </table>
        <p class="upo-submit">
            <input type="submit" name="update_options" class="button-primary" value="<?php _e('Save Changes','demo'); ?>" />
        </p>
        </form>
    </div>
</div>
<?php
}
endif;

So, How can I fix it?

Thanks!

2

This is because when a checkbox isn't checked it didn't send to the server. This is why the POST array doesn't have the upo_enable index.

You can, however, check if the value is empty or not:

$upo_enable = !empty($_POST['upo_enable']) ? true : false;

Or

$upo_enable = !empty($_POST['upo_enable']) ? $_POST['upo_enable'] : false;

More on this: https://www.w3.org/TR/html401/interact/forms.html

checkboxes

Checkboxes (and radio buttons) are on/off switches that may be toggled by the user. A switch is "on" when the control element's checked attribute is set. When a form is submitted, only "on" checkbox controls can become successful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.