0

I have a bootstrap 4 switch that is a custom checkbox input type introduced from the 4.3 version. I want to integrate it in a custom option page and assign to it a default value when my option page is rendered. How I can do this, is possible?

here is my actual code, I've omitted the add_action functions but there are present on the plugin code.

function registerSettings()
  {
    $menu_slug = 'my-plugin-options';
    register_setting( $menu_slug, 'my-option' );
    // I want to use these two functions but I'm not able to output the form so I've commented them 
    //add_settings_section( '', 'Slider settings', '', $menu_slug );
    //add_settings_field( '', 'Auto init', [$this, 'initSettings'], $menu_slug, '' );
  }


function renderOptionsMenu()
  {
    ?>
      <div class="container-fluid">
        <div class="row">
          <h1>Bootstrap Shortcodes - Swiper settings</h1>
          <form action="options.php" method="POST">
            <?php
              settings_fields('my-plugin-options');
              do_settings_sections('my-plugin-options');
            ?>
              <div class="custom-control custom-switch">
                <input type="checkbox" class="custom-control-input" name="my-option" id="customSwitch1" value="<?php echo esc_attr( get_option('my-option') ); ?>">
                <label class="custom-control-label" for="customSwitch1">Auto init</label>
              </div>
            <?php
              submit_button();
            ?>
          </form>
        </div>
      </div>
    <?php
  }

0

You can use the checked function for this.

https://codex.wordpress.org/Function_Reference/checked

The value attribute just indicates the value to be saved if the box is checked. eg.

<input type="checkbox" class="custom-control-input" name="my-option" id="customSwitch1" value="1" <?php checked( '1', get_option('my-option'), true ); ?>>
2
  • I've read about this function but I want to understand how it exactly work. I want to have the switch that initially is set to 0 so the switch is disabled. I've tried to save the value, after clicking it's supposed that the value become 1, but the value will be always 0 and will not change. – userone2 Oct 13 '19 at 12:36
  • it's a simple function which just compares the first argument to the second and echoes "checked" if the third argument is true. you could do the same with <?php if ( get_option('my-option') == '1' ) {echo " checked";} ?> or even just <?php if (get_option('my-option')) {echo " checked";} ?> since 1 will evaluate to true and empty/false/0 will evaluate to false. – majick Oct 13 '19 at 13:16

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.