Yayun
Yayun

Reputation: 11

Save Selected Option On Theme Option Wordpress

I have simple code, this code used to Theme Option

<?php function options_page() {
    if ($_POST['update_options'] == 'true') {
        update_option('color', $_POST['color']);
    }
    ?>

    <div class="wrap">
        <div id="icon-options-general" class="icon32"><br /></div>
        <h2><?php _e('Setting Theme', 'academi'); ?></h2>

        <form method="post" action="">
            <input type="hidden" name="update_options" value="true" />

            <table class="form-table">
                <tr valign="top">
                    <td class="tdleft"><label for="color"><?php echo get_option('color'); ?> <?php _e('Color Style: ', 'academi'); ?></label></td>
                    <td>
                        <select name="warna" id="warna">
                            <option value="">Change Fav Color</option>
                            <option value="aka-red" <?php echo (get_option('color'))? 'selected="selected"' : ''; ?>>Academi Red</option>
                            <option value="aka-green" <?php echo (get_option('color'))? 'selected="selected"' : ''; ?>>Academi Green</option>
                            <option value="aka-purple" <?php echo (get_option('color'))? 'selected="selected"' : ''; ?>>Academi Purple</option>
                        </select>
                    </td>
                </tr>
            </table>

            <input class="submit" type="submit" value="Save Change" />
        </form>
   </div>
<?php } ?>

Data option success to save in database, but selected option always on Academi Purple. Example I choose "Academi Red" in option select and than Save; this data save in database successfully but selected option not on Academi Red but on Academi Purple.

Upvotes: 0

Views: 588

Answers (1)

Melissa Freeman
Melissa Freeman

Reputation: 106

Your code is pretty tricky to read.

<?php echo (get_option('color'))? 'selected="selected"' : ''; ?>>Academi Purple</option>

This is your conditional statement.

What it is saying is IF get_option('color'), THEN set selected="selected".

As soon as your option 'color' has been set, this statement will ALWAYS return true. So all your options will be "selected", and the last one will "win".

You need to modify this statement.

echo ((get_option('color') === 'aka-purple') ? 'selected="selected"' : '');

Upvotes: 1

Related Questions