use*_*845 2 wordpress redirect
我在 example.com 上有一个 WordPress 网站,在 example.com/landing-page 上有一个登陆页面。登陆页面有一个表格供用户填写以获得免费咨询。
有没有办法安装 cookie 或其他东西,以便首次访问者访问 example.com 时,他们会被重定向到 example.com/landing-page。但是,在他们填写登陆页面上的表单后,下次访问 example.com 时,他们将看到常规主页(不会被重定向)。
您可以使用 javascript 来实现此目的。确保您已包含 jQuery。
将以下内容添加到两个页面都包含的全局 javascript 文件中,因为我们将在主页和登陆页面上使用这些辅助函数来检查 cookie 是否存在并创建它。
<script>
function create_cookie(name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime( date.getTime() + (days*24*60*60*1000) );
expires = "; expires=" + date.toGMTString();
}
document.cookie = name + "=" + value + expires + "; path=/";
}
function get_cookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) === ' ') {
c = c.substring(1, c.length);
}
if (c.indexOf(nameEQ) === 0) {
return c.substring(nameEQ.length, c.length);
}
}
return null;
}
</script>
Run Code Online (Sandbox Code Playgroud)
在您的主页上包含以下脚本,该脚本主要检查 cookie 'form_subscribed' 是否存在,如果不存在,则将用户重定向到登录页面。
<script>
// Redirect to landing page if 'form_submitted' cookie does not exist
if ( get_cookie( 'form_submitted' ) === 'undefined' ) {
window.location.href = "http://xxx.com/landing-page";
}
</script>
Run Code Online (Sandbox Code Playgroud)
在登陆页面上,您需要添加以下 javascript,它绑定一个监听事件以提交表单,当它发生时,它会创建 cookie,因此下次用户访问主页时,他们将不会被重定向。
<script>
jQuery(document).ready(function($) {
// Listen for the form submit event
$('#form-id').on('submit', function(){
// Create cookie so that the user is no longer redirected
create_cookie('form_submitted', 'true', 30);
});
});
</script>
Run Code Online (Sandbox Code Playgroud)
我希望这有帮助。祝你好运!=)
编辑:我刚刚在写答案时阅读了您原始帖子上留下的评论。只是想补充一点,我添加的 create_cookie 函数允许您在希望 cookie 过期之前传入天数(在我的示例中为 30),以便您可以将其设置得相当高以使其持续更长时间。
显然,JavaScript cookie 始终存在人们清除浏览器 cookie 的风险,但没有其他方法可以在未登录的用户上跟踪类似的内容。就用户无法删除它而言,更安全的是 PHP 会话存储在服务器上,但这比这要困难得多,而且即使这也不是万无一失的,因为您用来将用户与会话相关联的用户数据可能会发生变化,例如他们的 IP、浏览器等,因此始终存在风险。
您可以在表单页面上看到一个链接,上面写着“我已经完成了此表单,请带我到主网站”,该链接会再次设置 cookie。
最后,您会注意到我的解决方案是轻量级的,并且不包含不必要的插件,例如 $.cookie,因为我在很大程度上使用了 javascript,仅使用 jQuery 来准备文档并绑定提交事件。
| 归档时间: |
|
| 查看次数: |
7802 次 |
| 最近记录: |