如何在 WordPress 中使用 PHP 提交自定义表单后实现重定向?
<?php
if(isset($_POST['send'])) {
$email = trim($_POST['email']);
if(empty($email)) {
echo '<div class="error">Please enter your email.</div>';
} else {
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo '<div class="error">Email is not valid.</div>';
} else {
//redirect
?><script>window.location = "<?php echo home_url('/thank-you/');?>"</script><?php
}
}
}
?>
<form method="post" role="form">
<div class="form-group">
<label for="email">Email</label>
<input type="text" class="form-control" id="email" name="email" value="<?php if(!empty($email)) echo $email; ?>" placeholder="Enter your email..." />
</div>
<button type="submit" name="send" class="btn btn-default">Send</button>
</form>
这是自定义表单的简单实现,我想在提交后重定向到另一个网站。它已经可以与 javascript 一起使用,但也许存在更好的方法来使用 PHP 实现此重定向?
如有任何帮助,我们将不胜感激。谢谢!
试试这个
<?php wp_redirect( home_url('/thank-you/') ); exit; ?>
您也可以考虑这2个解决方案
第一个解决方案,在functions.php中创建一个用于java脚本重定向的函数,并在需要时调用,就像这样
function redirect($url){
$string = '<script type="text/javascript">';
$string .= 'window.location = "' . $url . '"';
$string .= '</script>';
echo $string;
}
第二个解决方案是让你的 WordPress index.php 看起来像这样
ob_start();
/*content of your index.php here*/
ob_flush();
您可以使用
wp_redirect(home_url('/thank-you/'));
或 header('Location: '.home_url('/thank-you/'));
。在某些情况下,只有后者对我有用。至于使用 javascript 来做这件事,当你有专门的 HTTP 标头时,它没有多大意义。