I’m a little stumped on this one. I’m not very experienced when it comes to PHP, but I have figured out how to display a value inputted from a text box. I’m now trying to do the same with a radio button.
My ultimate goal is to allow the site admin to be able to change the color of the theme by selecting from a few options. I want to be able to change CSS depending on what option is selected
As of right now, I’m basically just trying to display any kind of value on the site, such as displaying <p>Golden Theme</p>
in the header or something, just to get it to work.
Below I have the values set to 0, 1, 2, 3 in hopes to get that to display on my site dependent on what radio button is selected in the options menu.
Heres my current code
function colorSelector(){
?>
<h3 class="title">Set Theme Color</h3>
<form method="post" action="options.php">
<?php settings_fields('colorSelector-settings-group'); ?>
<div>
<input type="radio" id="goldTheme" name="colorSelect" value="0" <?php checked( '0', get_option( 'colorSelect' ) ); ?> checked>
<label for="goldTheme">Golden (Default)</label>
<input type="radio" id="monochromeTheme" name="colorSelect" value="1" <?php checked( '1', get_option( 'colorSelect' ) ); ?>>
<label for="monochromeTheme">Monochrome</label>
<input type="radio" id="greenTheme" name="colorSelect" value="2" <?php checked( '2', get_option( 'colorSelect' ) ); ?>>
<label for="greenTheme">Green</label>
<input type="radio" id="blueTheme" name="colorSelect" value="3" <?php checked( '3', get_option( 'colorSelect' ) ); ?>>
<label for="blueTheme">Blue</label>
</div>
<div>
<?php submit_button(); ?>
</div>
</form>
<?php
}
function add_colorSelector_options_page(){
add_menu_page('Color Selector', 'Color Selector', 'manage_options', "manage-colorSelector-options", "colorSelector");
add_action('admin_init', 'colorSelector_custom_settings');
}
function colorSelector_custom_settings(){
register_setting('colorSelector-settings-group', 'colorSelect');
}
add_action('admin_menu', 'add_colorSelector_options_page');
And this is the code I’m attempting to use to display the selected value in HTML
<?php echo get_option('colorSelect'); ?>
What am I missing? Any help would be appreciated
1 Answer
Your form is sending data using POST
method, so you should receive selected value of radio button in $_POST['colorSelect']
.
To simply display it you can use:
if(isset($_POST['colorSelect']))
echo $_POST['colorSelect'];
else echo "Nothing selected";
To save it to options table use following code at the start of your function colorSelector()
:
if(isset($_POST['colorSelect']))
update_option('colorSelect', $_POST['colorSelect']);
So you can always retrieve it later using get_option('colorSelect');
I hope this will help.
It is advised for best practice that you should follow WordPress Setting API, if you have more options to save.