manuel silva
manuel silva

Reputation: 95

Save form value into wordpress database

I'm creating a wordpress plugin, and I want to save a radio button value into the wordpress database, so I can use it later on another function. But I don't know how to do it. I tried with session but this value is lost when the session expired. Can you tell me how to do it?

Here is my code:

function e_option_page() { ?>
    <form action="" id="testimonialsform" method="post">
        <input type="radio" name="Option" value="Option 1">Option 1
        <input type="radio" name="Option" value="Option 2">Option 2
        <input type="radio" name="Option" value="Option 3">Option 3
        <input type="submit" name="submit" value="Submit" />
    </form>
    <?php
    if (isset($_POST['submit'])) {
        if(isset($_POST['Option'])){    
            echo "You have selected :".$_POST['Option'];  //  Displaying Selected Value
        }//End isset
    }//End isset
}//End function


function e_setting_page() {
    add_submenu_page('edit.php?post_type=testimonials', 'Settings', 'Settings', 'edit_posts', "settings",'e_option_page');
}

add_action('admin_menu' , 'e_setting_page'); 

Upvotes: 1

Views: 3009

Answers (2)

Shapon Pal
Shapon Pal

Reputation: 1146

You can save any option value in "wp_usermeta" table.

if (isset($_POST['submit'])) {
    if(isset($_POST['Option'])){
        //echo "You have selected :".$_POST['Option'];  //  Displaying Selected Value
        // Save data 
        global $wpdb;
        $table = $wpdb->prefix.'usermeta';
        $data = array('meta_key' => 'your_option_name', 'meta_value' => $_POST['Option']);
        $format = array('%s','%s');
        $wpdb->insert($table,$data,$format);
        $my_id = $wpdb->insert_id;
        print_r($my_id);
    }//End isset
}//End isset

After that you can use this for you option selected value.

Now you can check the option value.

// So check and make sure the stored value matches $new_value.
if ( $new_value = get_user_meta( $user_id=0,  'your_option_name', true ) ) {
    echo $new_value;
}else{
    wp_die( __( 'An error occurred', 'textdomain' ) );
}

Also you can update meta key

// Will return false if the previous value is the same as $new_value.
$updated = update_user_meta( $user_id=0, 'your_option_name', 'new_value' );

Upvotes: 1

Martin Cup
Martin Cup

Reputation: 2582

If you create a bigger plugin you maybe create your own table and store the data there. For simple things, this should be enough to store some setting values.

Upvotes: 0

Related Questions