問題描述
我正在嘗試使用 wp_redirect()在頁面上成功提交登入檔單後重定向使用者。
它不工作,並顯示以下錯誤:
Warning: Cannot modify header information – headers already sent by (output started at /Applications/MAMP/htdocs/theme/wp-content/themes/test/header.php:10) in /Applications/MAMP/htdocs/theme/wp-includes/pluggable.php on line 1178
我知道以前已經輸出了,這就是為什麼它不工作,但我不知道如何使這項工作。
登入檔單由函式呈現,並由我的 functions.php 內的另一個函式提交。
if ( isset( $_POST['subscribe'] ) ) {
// Submits the form and should then redirect
wp_redirect("/thank-you/");
exit;
}
那麼這兩個函式都用在我想要顯示登入檔單的地方。
恐怕這不是最好的事情。我應該創造一些這樣做的行動,但我不知道如何實現。我找到的大部分教程直接顯示在同一頁面上的結果,不需要額外的重定向。也許這就是為什麼他們正在使用 functions.php 中的函式
最佳解決方案
找到答案 (via)
而不是使用該函式,我向”wp_loaded” 新增了一個操作,這樣可以確保在任何標頭檔案傳送之前載入它。
<?php
add_action ('wp_loaded', 'my_custom_redirect');
function my_custom_redirect() {
if ( isset( $_POST['subscribe'] ) ) {
$redirect = 'http://example.com/redirect-example-url.html';
wp_redirect($redirect);
exit;
}
}
?>
次佳解決方案
您必須在 get_header()之前使用 wp_redirect(),否則不會顯示標題錯誤。
第三種解決方案
add_action('template_redirect', function(){
if(isset($_POST['subscriptio'])){// make this condition such that it only matches when a registraiotn form get submitted
/**
* do your stuff here
*/
wp_redirect();//....
}
});
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。