Good morning. I have a problem with a plugin made on the codex php of wordpres, that contains a list of forms and a form field to update/insert a new one.
The readdress to the list page after an upsert operation doesn’t work The operation works perfectly on the database, but the readdressing to the form list page doesn’t work and always return this error:
Warning: Cannot modify header information – headers already sent by …” and then refers tp
…by (output started at C:MAMPhtdocswordpresswp-adminmenu-header.php:171) in C:MAMPhtdocswordpresswp-includespluggable.php on line 1435. This is the code :
<?php
function upsertTile(){
ob_start();
$id = null;
if (isset($_GET['id'])) {
$id = $_GET['id'];
}
$selected_id = isset($_GET['selected_id']) ? sanitize_text_field($_GET['selected_id']) : null;
if ($selected_id) {
global $wpdb;
$table_name = $wpdb->prefix . 'cf9';
$selected_element = $wpdb->get_row(
$wpdb->prepare("SELECT * FROM $table_name WHERE id = %d", $selected_id)
);
}
if (isset($_POST['cf9_submit'])) {
if (isset($_POST['cf9_nonce']) &&
wp_verify_nonce($_POST['cf9_nonce'], 'cf9_form_submit')) {
$name = sanitize_text_field($_POST['cf9_name']);
$message = sanitize_textarea_field($_POST['cf9_message']);
// Salva su database
global $wpdb;
$table_name = $wpdb->prefix . 'cf9';
if ($id == null) {
$wpdb->insert(
$table_name,
array(
'time' => current_time('mysql'),
'name' => $name,
'message' => $message
)
);
} else {
$wpdb->update(
$table_name,
array(
'time' => current_time('mysql'),
'name' => $name ?? $selected_element->name,
'message' => $message ?? $selected_element->message,
),
array(
'ID' => $id
)
);
}
// Redirect to a different page
wp_redirect(home_url(SLUG_PAGE), 302);
ob_end_clean();
exit;
} else {
echo '<p>Nonce verification failed.</p>';
}
if (isset($_GET['cf9_status']) && $_GET['cf9_status'] == 'success') {
echo '<p>Thank you for your message!</p>';
}
}
ob_end_flush(); // Invia l'output del buffer al browser e termina il buffering
}
?>
I tried to add “exit;” after each wp_redirect and add ob_start() and ob_end_flush() at the beginning and end of the method but it doesn’t work and it gives always the same problem.
I tried even to substitute wp_redirect with header(“Location :form-list.php”) but there’s no extra fat.
I simply expect to execute my upsert operation and to return to the home page of the plugin (form-list.php) , which has slug ‘c9-form-list’, and return a message (“Thank you for your message!” or in case “Nonce verification failed.” ).