ChrisP777 ChrisP777 - 1 year ago 59
jQuery Question

using wp_authenticate() to redirect certain users when logging in

Our website is using Wordpress - WooCommerce login page for customers to login.

I am trying to use wp_authenticate() to achieve the following:

1) Customer login to our new website, enter their username and password, and hit Login button. In case you want to see WooCommerce Login file, click here.

2) Our new website goes through list see if the username matches. If the username matches, don't even look at the password, just redirect the user to other url such as

3) if the username doesn't match with our list, just let them login as usual.

With JQuery, someone helped me to come up with the following code:

var names = new Array(”BILL”, ”JIM”, ”BOB”); // get all names into array, and all in uppercase
var dest_url = ””; // URL we want to send them to
jQuery(document).ready(function () {
event.preventDefault(); // prevent default form action
var current_name = jQuery(”#username”).val();
current_name = current_name.trim().toUpperCase();
if ( -1 != jQuery.inArray(current_name, names) ) {
alert(”Redirecting ” + current_name + ” to ” + dest_url);
window.location = dest_url; // send to desired URL
document.getElementsByClassName(”login”)[0].submit(); // input name not on our list, so just do normal submit action

But I am not sure if wp_authenticate() can actually contain jquery script inside. Any suggestion would be greatly appreciated.

Answer Source

First, I would recommend doing this in PHP, not javascript.

Second, you have a couple of options, leveraging the built-in functionality of WordPress.

If all you care about is the username, and do not care if they successfully logged in with the right password, then you could leverage the filter found in wp_authenticate()

// This is the filter wp_authenticate fires
apply_filters( 'authenticate', null, $username, $password );

Knowing that, you could write a quick little plugin, or add this code to your theme's functions.php file:

// Run this filter with priority 9999 (last, or close to last), after core WP filters have run
add_filter('authenticate', 'redirect_certain_users', 9999, 3);

// Your custom filter function
function redirect_certain_users( $user, $username, $password) {
    // Assumes you write a function called get_list_of_users_to_redirect that returns an array similar to that in your sample code
    $redirect_users = get_list_of_users_to_redirect();

    // If the user is in the array of users to redirect, then send them away
    if ( in_array( $username, $redirect_users ) ) {

    return $user;

Note that this code is untested, but should get you at least 90% of the way there.