以下问题:我在php中检查插件页面的条件,如果是false,我想重定向到另一个页面。
使用PHP,它将简单地为:
header('Refresh: 10; URL=http://yoursite.com/page.php');
如果你想在10秒后重定向。但是在Wordpress中,会出现"headers already sended"的错误。
它的wordpress功能是:
exit( wp_redirect( admin_url( 'admin.php?page=your_page' ) ) );
但是该函数没有时间参数。
我知道如何使用javascript重定向,但我更愿意使用php/wordpress函数。有办法做到这一点吗?
您必须能够以某种方式修改文档的<head>
部分,并添加以下元标记:
<meta http-equiv="refresh" content="10; URL=http://yoursite.com/page.php">
这将是不同的,取决于你的模板结构。
在wordpress中修改head部分(而不是使用模板)的通用解决方案是添加wp_head操作:
<?php
add_action('wp_head', 'some_function');
function some_function() {
if($someCondition) { ?>
<meta http-equiv="refresh" content="10; URL=http://yoursite.com/page.php"> <?php
}
}
php代码是服务器端的,经过处理后传递给客户端。
简单的解决方法:
使用一个特殊的头并输出正常的html重定向头
好吧,似乎没有简单的PHP解决方案来解决这个问题,所以我创建了一个javascript解决方案。似乎是处理重定向的最简单方法:
if($my_condition == false){ ?>
<script type="text/javascript">
$(document).ready(function() {
var redirection_link=<?php echo json_encode(admin_url( 'admin.php?page=my_plugins_settings_page' )); ?>;
alert('Please check your Settings first!');
window.location.replace(redirection_link);
});
</script>
<?php
}
此代码需要在标头上,您可以制作一个额外的header-extra.php并将此代码放入中
在您想要重定向的页面中,添加到get_header('extra');变量$dw_attachment_url是url、图像id或您想要重定向的任何内容
header-extra.php
<head>
<meta http-equiv="refresh" content="10;url=<?php echo $dw_attachment_url ?>" />
<script>
var seconds = 0;
function displayseconds() {
seconds += 1;
document.getElementById("secondsdisplay").innerText = "This page will be redirect in " + seconds + " seconds..";
}
setInterval(displayseconds, 1000);
function redirectpage() {
window.location = "<?php echo $dw_attachment_url ?>";
}
</script></head>
page.php
get_header('extra');
不,一旦PHP发送了标头(在本例中是整个页面),n秒后就无法执行此操作。
一个可能错误的选项是让PHP使用Sleep(5)保持渲染一段时间,但这不是一个好的选项。
最佳解决方案:覆盖函数"wp_redirect"并设置一个类似的附加参数
wp_redirect($page, $interval = 20)
请确保将$inverval设置为20,否则使用此函数的其他脚本可能会失败。