How to create a multiple choice radio group for a single theme option

Logically, I’m thinking it should something like…

<input type="radio" id="my_category_layout">
    <option value="Item1">Item 1</option>
    <option value="Item2">Item 2</option>
    <option value="Item3">Item 3</option>
</input>

But from what i’ve seen radio buttons dont markup like that.

Read More

My existing code is below that creates a select list pulldown menu that allows me to capture a selected value. I’m struggling with how to convert this into a radio group.

The main issue is that there is only one ID to represent the select, but I can’t figure how to create three radio buttons with a single ID value that can be passed to represent the selected button.

How would I do that? Here’s my existing code for creating a select with a single id and multiple values…

<?php
$mySelectOptions = array("list" => "List View", "grid1" => "Grid View Multi Column", "grid2" => "Grid View Two Column");

array(  "name" => "Category Layout",
     "desc" => "description goes here",
     "id" => "my_category_layout",
     "type" => "select",
    "options" => $mySelectOptions ),
?>
<form method="post">

<?php foreach ($options as $value) 
{
    switch ( $value['type'] ) 
    {
    case "select":
    ?>
    <select class="input" name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>">
    <?php foreach ($value['options'] as $option) { ?>
        <option<?php if ( get_settings( $value['id'] ) == $option) { echo ' selected="selected"';
        } 
        elseif ($option == $value['std']) 
        { 
        echo ' selected="selected"'; 
        } ?> value='<?php echo $option; ?>'>
        <?php echo $option; ?></option><?php } ?>
    </select>
<?php
break;
case "radio":
?>

Related posts

Leave a Reply

1 comment

  1. case "radio":
      foreach ($value['options'] as $option) { ?>
         <label for="<?php echo "{$value['id']}_{$option}"; ?>">
         <input
            type="radio"
            name="<?php echo $value['id']; ?>"
            id=<?php echo "{$value['id']}_{$option}"; ?>
            value="<?php echo $option; ?>"
            <?php checked($option, get_settings($value['id'])); ?>
         />
         <?php echo $option; ?>
         </label>
      <?php }
    break;
    

    But I don’t recommend coding theme/plugin settings this way.

    The array above doesn’t just represent the option:value, but also the type of input, possible values (description, id?)… This just feels wrong. And you’re making the code lack flexibility.

    What if you decide later to change a select field with a radio field?
    Or what if you want to add a image describing the option, or a color picker?

    Why do you think WP’s core options are not coded this way?