Topic: Radio Buttons Function
Hi
If someone find this useful
I was needing radio buttons to work dinamically in frontaccounting and I could't find anything, so I decide to create a function to do so:
function dynamic_radio_row(
$label,
$name,
$options = [],
$selected,
$orientation = 'vertical',
$default = null
)
{
$current = ($selected == null || $selected == ' ') ? $default : $selected;
$separator = $orientation === 'horizontal' ? " " : "<br><br>";
echo "<tr><td class='label'>".htmlspecialchars($label, ENT_QUOTES)."</td><td>";
foreach ($options as $value => $text)
{
$checked = ($value === $current) ? " checked" : "";
echo "<input type='radio' "
. "name='" . htmlspecialchars($name, ENT_QUOTES) . "' "
. "value='" . htmlspecialchars($value, ENT_QUOTES) . "'"
. $checked
. "> " . htmlspecialchars($text, ENT_QUOTES)
. $separator;
}
echo "</td></tr>";
}
How you call it:
/**
* @param string $label
* @param string $name
* @param array $options
* @param string $selected Selected value (could be POST)
* @param string $orientation 'vertical' | 'horizontal' depending how you want to display the values
* @param string $default Default value if $selected is null, empty or a blank space.
*/
// Array with the neccesary options for the radio Button
$opts = [
'ONE' => _('First'),
'TWO' => _('Second'),
'THREE' => _('Third'),
'FOUR' => _('Fourth'),
];
dynamic_radio_row(_('Select Option:'), 'my_field', $opts, get_post('my_field'), 'vertical', 'ONE');