• I am building a ‘test’ wordpress plugin which should have 3 options from a select form in the admin page. When an option is selected, it should invoke a function.

    Using update_option, I have this:

    The code:

    <select name="pytime">
            <option value="1">time</option>
            <option value="2">date</option>
            <option value="3">date-time</option>
        </select>
    
    <?php
    $pytime = $_POST['pytime'];
    if($pytime == 1) {
        function add_copyright() {
            $copyright_message = "Copyright ". date(Y)  . ", All Rights Reserved";
            echo '<div id="plugin-copyright">' . $copyright_message . '</div>';
        }
        add_action("wp_footer",add_copyright);
    }
    
    if($pytime == 2) {
        function func2() {
           // func2 code
        }
        add_action("wp_footer",func2);
    }
    
    if($pytime == 3) {
        function func3() {
           // func3 code
        }
        add_action("wp_footer",func3);
    }
    
    $option_name = 'time' ;
    $new_value = $_POST['pytime'];
    
    if ( get_option( $option_name ) !== false ) {
    
        // The option already exists, so we just update it.
        update_option( $option_name, $new_value );
    
    } else {
    
        // The option hasn't been added yet. We'll add it with $autoload set to 'no'.
        $deprecated = null;
        $autoload = 'no';
        add_option( $option_name, $new_value, $deprecated, $autoload );
    }

    What should I set $option_name and $new_value to in order to select the appropreiate function?

Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    How you store the value is OK as is, but what is stored has nothing to do with picking functions, you are not using get_option('time') to do anything. Assuming the POST action points back to this page, the function executed is based on $_POST[‘pytime’], the selected option. You could run the function based on get_option('time'), but this would run functions on the previously selected value, not the current selection.

    To reflect the current selection move the update_option() before the function selection.

    If you want to run a function based on the form selection, what is the point for saving the value, except perhaps to default to the previously selected option. In that case the options should look something like this:
    <option value="1" <?php if(1==get_option('time')) echo 'selected="selected"'; ?>>time</option>

Viewing 1 replies (of 1 total)
  • The topic ‘update_option based on selected option in admin panel’ is closed to new replies.