hlashbrooke / WordPress-Plugin-Template

A robust code template for creating a standards-compliant WordPress plugin.
https://hughlashbrooke.com/
GNU General Public License v2.0
1.03k stars 329 forks source link

checkbox default 'on' not working #71

Open alekseyn1 opened 5 years ago

alekseyn1 commented 5 years ago

Hello, checkbox default 'on' not working

when settings screen gets loaded the first time after plugin activation, the checkbox is unchecked.

I am on the latest WP (5.0.3) and PHP 7.2

Any help would be greatly appreciated

                array(  //A standard checkbox - if you save this option as checked then it will store the option as \'on\', otherwise it will be an empty string.
                    'id'            => 'enable_email_notification_checkbox',
                    'label'         => __( 'E-mail notification', 'test_plugin_text' ),
                    'description'       => __( 'Default is on. Select this option to enable a welcome email notification to new users created by this plugin. ', 'test_plugin_text' ),
                    'type'          => 'checkbox',
                    'default'       => 'on'
alekseyn1 commented 5 years ago

Here is a working solution. Replace the entire case: entry with this

            case 'checkbox':
                $checked = '';

                   global $wpdb;
                   $empty_option = false;
                   $row = $wpdb->get_row($wpdb->prepare("SELECT option_value FROM $wpdb->options WHERE option_name = %s LIMIT 1", $option_name));
                   if (is_object($row)) {
                       $empty_option = true;
                   }

                if( ($option) || ( $empty_option == false && $field['default'] ) ){
                    $checked = 'checked="checked"';
                }
                $html .= '<input id="' . esc_attr( $field['id'] ) . '" type="' . $field['type'] . '" name="' . esc_attr( $option_name ) . '" ' . $checked . '/>' . "\n";
            break;
jonathanbossenger commented 5 years ago

Hey @alekseyn1 thanks for this.

Are you able to open a pull request with these changes. I can't guarantee I will be able to merge it very soon, but if it's open I can at least try and prioritise it.