mercredi 29 juin 2016

wordpress settings save and read from database

I have options menu in wordpress.

I have option where you can put number.

$num_opts = 'num_opts';
$hidden_num_opts = 'return_num_opts';
$num_opts_field = 'num_opts';
$num_opts_value = get_option( $num_opts );

so I get options value from db

if(( isset($_POST[ $hidden_num_opts ]) && $_POST[ $hidden_num_opts ] == 'Y' ){
$num_opts_value = $_POST[ $num_opts_field ];
 update_option( $num_opts, $num_opts_value);
}

and if value changes we save it to db.

and here is the form. Values get updated when save is pressed. Page gets reloaded and new value is shown in field.

<form name="options_form" method="post" action="">
<input type="hidden" name="<?php echo $hidden_num_opts; ?>" value="Y">

<p><?php _e("Number of options:", 'x' ); ?> 
<input type="text" name="<?php echo $num_opts_field; ?>" value="<?php echo     $num_opts_value; ?>" size="5">
</p><hr />

<?php

$options = array();
for ($opts = 1; $opts <= $num_opts_value; $opts++){
    array_push($options,$opts); 
}

foreach ($options as $option) {
$opt_val = get_option($option);
echo '<input type="hidden" name="hidden_' . $option . '" value="Y">';
echo '<br>';
printf( __('Option %s', 'x'), $option);
echo '<br>';
echo '<input type="text" name="' .  $option . '" value="'. $opt_val .'" size="10">';
echo '<br>';
if(( isset($_POST[ 'hidden_'.$option ]) && $_POST[ 'hidden_'.$option ] == 'Y' )){
update_option($option, $_POST[$option]);
}
}

unset($option);



?>

<p class="submit">
<input type="submit" name="Submit" class="button-primary" value="<?php esc_attr_e('Save Changes') ?>" />
</p>

</form>

Based on number inserted in first field I create other field. So if we enter 5 when page reloads we get 5 new input fields. We can enter text in it and when we press save everything is saved in db. So we get field id of option name and value of option value.

But page reloads and values aren't shown. When I reload page again value shows.

So for the 1st input I type x and x is saved in db but in input field nothing is shown. When I reload page x is shown. If I then write b instead of x I got b saved and x shown until I reload page. If I don't reload page and just enter new value page gets reloaded and old value is shown.

Any tips?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire