【发布时间】:2012-09-11 13:16:25
【问题描述】:
我创建了一个双语言网站,其表单在提交时会保存一个 cookie,然后每个页面都会检查 cookie 以查看要加载的语言。
我遇到的问题是提交按钮需要按两次才能加载页面并切换语言。
这是我的表格:
<form action="<?php the_permalink(); ?>" name="region" method="post">
<input type="submit" name="region" value="English" id="en-button" />
<input type="submit" name="region" value="Cymraeg" id="cy-button" />
</form>
这是在我的functions.php文件中保存cookie:
function set_region_cookie()
{
if(isset($_POST['region']))
{
// Set Cookie
setcookie('region', $_POST['region'], time()+1209600);
// Reload the current page so that the cookie is sent with the request
header('Region: '.$_SERVER['REQUEST_URI']);
}
}
add_action('init', 'set_region_cookie');
这就是我在每个内容区域周围加载不同内容的内容:
<?php $language = $_COOKIE["region"];
if ($language == "English") { ?>
<?php echo the_field('english_content'); ?>
<?php } else { ?>
<?php echo the_field('welsh_content'); ?>
<?php } ?>
语言会正确切换,但只有在您单击提交按钮两次时才能正确切换。
【问题讨论】:
-
所以你是说第一次点击
submit按钮时,表单未提交?如果是这样,您使用的是什么浏览器,所有浏览器都会出现这种情况吗? -
@deifwud 当我单击提交按钮时,页面会重新加载,然后当我再次单击它时,页面会重新加载,但这次语言实际上发生了变化。因此,要更改语言,我需要单击它两次。我正在使用 Chrome,但它发生在 Safari 和 Firefox 中。
-
好的 - 表单实际上正在提交 - 你是在调用
set_region_cookie之前分配$language = $_COOKIE['region']吗? -
@deifwud 我不太确定!
set_region_cookie在我的functions.php 文件中,表单在我的header.php 文件中。 -
我对 Wordpress 的设置了解不多,所以很遗憾,我无法为您提供太多帮助,请尝试找出在何处以及何时调用
set_region_cookie()函数。听起来您正在尝试在设置 cookie 之前分配$language = $_COOKIE['region'],这可以解释为什么它仅在第二次提交表单后才开始工作
标签: php html wordpress cookies