Skip to content

Instantly share code, notes, and snippets.

@gicolek
Last active September 2, 2017 16:16
Show Gist options
  • Save gicolek/a5936d06632546ed9521 to your computer and use it in GitHub Desktop.
Save gicolek/a5936d06632546ed9521 to your computer and use it in GitHub Desktop.
Username or Email login
<?php
//Заставляем работать форму авторизации GF
/*
* This hook fires after the form was submitted and the whole data was validate, we’ll bind it to the form which have just created.
*/
// the _14 prefix has to match the id of the form you have created
add_action( "gform_after_submission_14", "login_form_after_submission", 10, 2 );
function login_form_after_submission($entry, $form) {
// get the username and pass
$username_or_email = $entry[4];
// check if the user has provided an email
if ( strpos( $username_or_email, '@' ) ) {
if ( !is_email( $username_or_email ) and ! email_exists( $username_or_email ) ) {
// either email is wrong or the user with such an email doesn't exist
return;
} else {
$user = get_user_by( 'email', $username_or_email );
$username = $user->user_login;
}
} else {
$username = $username_or_email;
}
if ( !username_exists( $username ) ) {
return;
}
$pass = $entry[12];
$creds = array();
// create the credentials array
$creds['user_login'] = $username;
$creds['user_password'] = $pass;
// sign in the user and set him as the logged in user
$sign = wp_signon( $creds );
wp_set_current_user( $sign->ID );
}
/*
* This hook fires during the form submission process and iterates over every field.
*/
// the _14 prefix has to match the id of the form you have created
add_filter( "gform_field_validation_14", "login_validate_field", 10, 4 );
function login_validate_field($result, $value, $form, $field) {
// make sure this variable is global
// this function is fired via recurrence for each field, s
global $user;
// validate username
if ( $field['cssClass'] === 'username' ) {
// check if the user has provided an email
if ( strpos( $value, '@' ) ) {
if ( !is_email( $value ) and ! email_exists( $value ) ) {
$result["is_valid"] = false;
$result["message"] = "Invalid email provided.";
} else {
$user = get_user_by( 'email', $value );
}
} else {
$user = get_user_by( 'login', $value );
if ( empty( $user->user_login ) ) {
$result["is_valid"] = false;
$result["message"] = "Invalid username provided.";
}
}
}
// validate pass
if ( $field['cssClass'] === 'password' ) {
if ( !$user or ! wp_check_password( $value, $user->data->user_pass, $user->ID ) ) {
$result["is_valid"] = false;
$result["message"] = "Invalid password provided.";
}
}
return $result;
}
// Auto login to site after GF User Registration Form Submittal
function we_autologin_gfregistration($user_id, $config, $entry, $password) {
wp_set_auth_cookie( $user_id, false, '' );
}
add_action( 'gform_user_registered', 'we_autologin_gfregistration', 10, 4 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment