WordPress.org

Ready to get started?Download WordPress

Forums

How to create radio button in options page? (3 posts)

  1. ak47marx
    Member
    Posted 3 years ago #

    Call me stupid but I coudn't figure out how to do it. For text input I would just:
    <input type="text" name="option_name" value="<?php echo get_option( 'option_name' ); ?>" />

    and then hook it into wordpress using register_setting(). I could then get its value thru get_option('option_name'). How should I do that with radio buttons?

    All im looking for is simple "yes" / "no" radio buttons.

    I can't seem to figure out how to register my yes / no options in db and how to get its value thru get_option('option_name').

    register_setting( 'baw-settings-group', 'chooseyes', 'yes' );
    register_setting( 'baw-settings-group', 'chooseno', 'no' );
    
    <input name="chooseyes" type="radio" value="0" <?php checked( '0', get_option( 'chooseyes' ) ); ?> />
    <input name="chooseno" type="radio" value="1" <?php checked( '1', get_option( 'chooseno' ) ); ?> />
  2. Simivar
    Member
    Posted 3 years ago #

    I have made it in this way:

    <input type="radio" id="[ID]" name="[NAME]" <?php if($[VARIABLE] == 'true') echo 'checked="checked"'; ?> value="true" />yes
    <input type="radio" id="[ID]" name="[NAME]" <?php if($[VARIABLE] == 'false') echo 'checked="checked"'; ?> value="false" />no
  3. ethanhackett
    Member
    Posted 2 years ago #

    @simivar that helped me a lot. I also would like to append to your code recomendation with an if empty boolean.

    If this is the first time the plugin has been installed, the page won't display a default value. I'd recommended adding a boolean that checks to see if the returned option has a value. If it's empty then assign it the default value true or false.

    Example:

    <?php
    // Retrieves the option using get_option(); and assigns it to a variable.
    $[VARIABLE] = get_option('[NAME]');
        // Checks to see if variable is empty. Ex: not yet defined by the users.
    	if(empty($[VARIABLE])){
            // If it is empty assign it your default value true or false.
    		$[VARIABLE] = "[FALSE/TRUE]";
    	}
    ?>

    This helps from a UX point of view. The users may not know whether something by default is yes or no. Going the extra step will be well worth it.

    Same Example No Comments:

    <?php
    $[VARIABLE] = get_option('[NAME]');
    	if(empty($[VARIABLE])){
    		$[VARIABLE] = "[FALSE/TRUE]";
    	}
    ?>

Topic Closed

This topic has been closed to new replies.

About this Topic