I’m trying to add a new function to a plugin for that I want to save the preferences on the options of WordPress to use on the front later, I made it update but it does only on 1 array instead of adding the array after the last 1, this is the code:
public
function hidden_callback() {
// getting data
$existing_data = get_option('dealer-settings-used-finance-custom-options', array());
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['dealer-settings-used-finance-custom-options'])) {
$input = $_POST['dealer-settings-used-finance-custom-options'];
if (isset($input['model']) && isset($input['start_year']) && isset($input['end_year']) && isset($input['term']) && isset($input['value'])) {
// new array using form data
$new_entry = array(
'model' => sanitize_text_field($input['model']),
'start_year' => absint($input['start_year']),
'end_year' => absint($input['end_year']),
'term' => absint($input['term']),
'value' => floatval($input['value']),
'iscpo' => isset($input['iscpo']) ? filter_var($input['iscpo'], FILTER_VALIDATE_BOOLEAN) : false,
);
// Check if $existing_data is an array, if not, initialize it
if (!is_array($existing_data)) {
$existing_data = array();
}
// Add the new object to the existing array
$existing_data[] = $new_entry;
// Update the option with the updated array
update_option('dealer-settings-used-finance-custom-options', $existing_data);
}
}
}
if I do a dd of the data stored I get:
array:6 [▼
"model" => "prueba test 2"
"start_year" => "2000"
"end_year" => "2002"
"term" => "20"
"value" => "2"
"iscpo" => "on"
]
after adding more data it overwrite the existing one instead of adding after, my desired output would be:
[
[
model=>'model1',
start_year=>1000,
end_year=>1001,
term=>10,
value=>1,
iscpo=>true,
],
[
model=>'model2',
start_year=>2000,
end_year=>2001,
term=>20,
value=>2,
iscpo=>false,
],
]
here is my function for displaying later:
public
function display_saved_data() {
// Asegurarse de que los datos se guardan correctamente
$saved_data = get_option('dealer-settings-used-finance-custom-options');
if (!empty($saved_data)) {
dd($saved_data);
echo '<h2>Saved Data:</h2>';
echo '<ul>';
echo '<li>';
echo 'Model: '.esc_html($saved_data['model']).
', ';
echo 'Start Year: '.esc_html($saved_data['start_year']).
', ';
echo 'End Year: '.esc_html($saved_data['end_year']).
', ';
echo 'Term: '.esc_html($saved_data['term']).
', ';
echo 'Value: '.esc_html($saved_data['value']).
', ';
echo 'Is CPO: '.($saved_data['iscpo'] == 'on' ? 'Yes' : 'No');
echo '</li>';
echo '</ul>';
}
}