So I have a basic wordpress plugin that has a form in the admin end. The form collects information via POST and inserts a record in the database and redirect to the edit page of the object created.
Step 1: get object fields from POST array
Step 2: insert code into database using $wpdb
Step 3: if insert was successful redirect to https://example.com
if( isset($_POST['submit'])){
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$result = $wpdb->insert('table', array('first_name' => $first_name, 'last_name' => $last_name), array('%s','%s'));
if($result){
$url = "https://example.com/";
header("Location: $url");
die();
}else{
echo "Error inserting record in table";
}
}
Now the expected result is that the page should redirect to https://example.com on successful insertion of object in the database. But I get a headers already sent error in PHP.
Interestingly, if I install and activate woocommerce in WordPress, the error vanishes and the expected output is achieved.
I'm curious as to how woocommerce does it.
When you use header()
function, you may experience these kind of warnings in WP. It's always a better approach to use wp_redirect()
instead:
wp_redirect( 'https://example.com/' );
exit;
Update:
Your function containing header send/modify data (eg wp_redirect
, header()
, etc.) must be invoked before any output is made by WP. Maybe you can test putting your function and the related hook, in another function which is hooked to init
or admin_init
action hooks?
Make sure none of your plugin files has any spaces or strings before PHP opening tag ( <?php
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.