[英]Redirect a user after login with ajax validation to the same page where he was
I am using this function to validate a user (ajax login) for my wordpress website.我正在使用此功能来验证我的 wordpress 网站的用户(ajax 登录)。
// Perform AJAX login on form submit
$('form#vbp-login-form').on('submit', function(e){
$('form#vbp-login-form p.status').show().text(ajax_login_object.loadingmessage);
$.ajax({
type: 'POST',
dataType: 'json',
url: ajax_login_object.ajaxurl,
data: {
'action': 'ajaxlogin', //calls wp_ajax_nopriv_ajaxlogin
'username': $('form#vbp-login-form #username').val(),
'password': $('form#vbp-login-form #password').val(),
'security': $('form#vbp-login-form #security').val() },
success: function(data){
$('form#vbp-login-form p.status').text(data.message);
if (data.loggedin == true){
document.location.href = ajax_login_object.redirecturl;
}
}
});
e.preventDefault();
});
After login the user is redirected to the home page not the page which he was on.登录后,用户被重定向到主页,而不是他所在的页面。 I want the user to be redirected to the same page where he came from.我希望用户被重定向到他来自的同一页面。 How can i do this ?我该怎么做?
Any kind help is appreciated.任何帮助表示赞赏。
PHP SOLUTION解决方案
I presume you are forming the ajax_login_object
array in PHP.我假设您正在 PHP 中形成ajax_login_object
数组。 Probably using可能使用
wp_localize_script( 'your_script', 'ajax_login_object' , $ajax_login_object );
That is the usual WordPress method of passing data to a front end script anyway.无论如何,这是将数据传递给前端脚本的常用 WordPress 方法。
Try this PHP:试试这个 PHP:
$ajax_login_object['redirecturl'] ="//".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
Or try this from http://www.insertcart.com/get-current-page-url-in-wordpress/ :或者从http://www.insertcart.com/get-current-page-url-in-wordpress/试试这个:
$ajax_login_object['redirecturl'] = esc_url(the_permalink());
Another alternative from http://mekshq.com/get-current-page-url-wordpress/ is: http://mekshq.com/get-current-page-url-wordpress/ 的另一种选择是:
global $wp;
$ajax_login_object['redirecturl'] = home_url(add_query_arg(array(),$wp->request));
JavaScript Solution JavaScript 解决方案
This is a pure JavaScript solution.这是一个纯 JavaScript 解决方案。
In JS window.location.href
returns the current URL of the page.在 JS window.location.href
返回页面的当前 URL。 So in your code you could replace所以在你的代码中你可以替换
document.location.href = ajax_login_object.redirecturl;
with与
document.location.href = window.location.href;
function ajax_login_init(){
wp_register_script('ajax-login-script', get_template_directory_uri() . '/ajax-login-script.js', array('jquery'));
wp_enqueue_script('ajax-login-script');
$ajax_login_object ="//".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
wp_localize_script('ajax-login-script', 'ajax_login_object', array(
'ajaxurl' => admin_url('admin-ajax.php'),
'redirecturl' => $ajax_login_object, //this line for same redirect
));
// Enable the user with no privileges to run ajax_login() in AJAX
add_action('wp_ajax_nopriv_ajaxlogin', 'ajax_login');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.