Wordpress - Form to match registered users - wordpress

I need to create a form on wordpress for registered users.
Users don't have to reach backend but they land on a page with just a form where they write their email and submit.
If the mail matches with the mail registered as user they'll be redirected to the next page.
If there's no matching mail on user list they just receive an error to try again.
It's for a kind of browser game...
Thanks

For checking whether an email exists or not, you can use the email_exists() function provided by WordPress.
Here's the example:
$email = 'myemail#example.com';
$exists = email_exists( $email );
if ( $exists ) {
echo "That E-mail is registered to user number " . $exists;
} else {
echo "That E-mail doesn't belong to any registered users on this site";
}
You can use it to define your logic.
And for redirection, WordPress has a function called wp_redirect()
Here's an exammple:
wp_redirect( 'http://www.mynewurl.com/blah/' ); exit;
Make sure to call exit just after calling that function.
And if you are having trouble figuring out how to know whether the user is actually a logged in user or not, you can use the is_user_logged_in() function.
Here's an example:
if ( is_user_logged_in() ) {
echo 'Welcome, registered user!';
} else {
echo 'Welcome, guest!';
}
Now you got all the functions needed to complete your task! Just make use of these functions properly based on your logic and you will be able to complete it!

Related

Wordpress custom login errors based on whether or not an advanced custom field is set true for that user

I have kind of a unique issue. I have migrated a website and rebuilt it on wordpress. Some of the users that were migrated over the passwords were not migrated with them. So for all the old users I added an advanced custom field named "password_reset" and set it to true for all the older users.
What I am trying to do is show a custom message for these users that says something like "we have updated our website please rest your password with a link to reset".
I have added the below code to a function in the functions.php file
//if migrated user needs to reset password
$username = $_POST['username'];
if (username_exists( $username ) && get_field( 'password_reset', 'user_'.$uid ) ) {
$error= 'Please reset your password. To reset your password click here.';
}
return $error;
since the user isn't logged in quite yet when they are to recieve this error, I am trying to use the username_exists(username). Basically I need to identify is the user name exists already and if that username has the acf field "password_reset" checked. So far I have had no luck, any help would be much appreciated.
UPDATE: here is my lates version: the messages for invalid username and incorrect password are working, Just can't get it to work with the usernames that hold the acf value
function my_custom_error_messages() {
global $errors;
$err_codes = $errors->get_error_codes();
// Invalid username.
if ( in_array( 'invalid_username', $err_codes ) ) {
$error = '<strong>ERROR</strong>: Invalid username.';
}
// Incorrect password.
if ( in_array( 'incorrect_password', $err_codes ) ) {
$error = '<strong>ERROR</strong>: The password you entered is incorrect.';
if (username_exists( $username ) && get_field( 'password_reset', 'user_'.$uid ) ) {
$error= 'Please reset your password. To reset your password click here.';
}
}
return $error;
}
add_filter( 'login_errors', 'my_custom_error_messages');
I believe the issue is that the username is not passed to the login_errors filter. The only data available within that filter is the error message that is passed (no definitive data about user accounts at all).
I have found a different reference that may shed some light on a way to provide a customized error message without using that filter. Try using the wp_authenticate_user filter, instead:
WordPress codex reference
https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_authenticate_user
Reference for application of code
https://backups.nl/internet/wordpress-revealing-username-login-trial-error/

Disable auto login upon registration in Wordpress

[update1] I am using the ClassiCraft theme and I have no idea where to customize the login and register forms
[update2] I know that the registration process does not go through wp_authenticate because I redefined it inside a plugin of mine
I am quite new in the Wordpress world (actually just got my hands on it for the first time yesterday) and I am having some difficulties finishing up a little project I am working on.
The project is rather simple (or so I thought) and consists in adding a confirmation link to email received upon registration in order to validate the email address provided to prevent using fake emails that the registrar does not even own.
I am about all done except that once I hit the register button it leads to log in the freshly created user.
I googled stuff like "wp disable auto login on registration" and whatnot but I have not been able to find anything that worked. I even tested a few plugins supposed to be doing exactly what I need but none of them worked.
Also, I am not using any plugins for the registration/login forms and it appears that the code in the wp-login.php file is actually not even used...
Would anyone have an idea? Thanks
Okay, so without an access to the theme, i can't really answer you.
But i can tell you what I would try.
1. Add action on user_register hook, to add a post meta that will be useful to check if user has confirm his email.
add_action( 'user_register', 'add_has_confirm_email_user_meta');
function add_has_confirm_email_user_meta( $user_id ) {
update_user_meta( $user_id, 'has_confirm_email', 0 );
}
2. Prevent the user from log in automatically after registration.
Here i can't tell you the hook that will works for you. For example, the hook for the wordpress registration is user_register, but if you have woocommerce, the hook I will use, would be woocommerce_registration_redirect. So try to find what hook is available after the registration with your theme.
In all case, the code in the function would be something like :
function custom_registration_redirect() {
// Log out the user
wp_logout();
// The login url could be an other, with woocommerce for example it is : get_permalink(get_option('woocommerce_myaccount_page_id')
$login_url = wp_login_url();
// Redirect on it
wp_redirect( $login_url);
exit;
}
It will also be necessary, to add a message on this page to alert the user, that he will receive an email to confirm his account.
3. Prevent user from login when he submit the log in form
Add action on wp_login hook to achieve that.
add_action('wp_login', 'prevent_user_from_login', 10, 2);
function prevent_user_from_login($user_login, $user = null ) {
if ( !$user ) {
$user = get_user_by('login', $user_login);
}
if ( !$user ) {
// not logged in
return;
}
// Get user meta
$has_confirm_email = get_user_meta( $user->ID, 'has_confirm_email', true );
if ( $has_confirm_email == '0' ) {
// Clear cookies, a.k.a log user out
wp_clear_auth_cookie();
$login_url = wp_login_url();
$login_url = add_query_arg( 'has_confirm_email', '0', $login_url);
wp_redirect( $login_url );
exit;
}
}
4. Add message on log in page if we get the has_confirm_email to 0
add_filter('login_message', 'has_not_confirm_email_login_message');
function has_not_confirm_email_login_message($message) {
if ( isset( $_GET['has_confirm_email'] ) && $_GET['has_confirm_email'] == 0 ) {
$message = '<div id="login_error">You have not confirmed your email.</div>';
}
return $message;
}
5. Send the email with a link to confirm his email.
You will need to generate a token to add to the url.
For the hook to change the default email sent by Wordpress, you can use wp_new_user_notification_email that is available since the 4.9 of Wordpress.
In the function itself you could do something like :
function wp_new_user_notification_email( $wp_new_user_notification_email, $user, $blogname) {
// Generate the token (there is other function available with php 7, but this one works great)
$token = bin2hex(openssl_random_pseudo_bytes(16));
// Add the token to the user
update_user_meta( $user->id, 'confirm_email_token', $token );
// Get your login url
$log_in_url = wp_login_url();
// Add user id and token to the url
$url = add_query_arg(
array(
'token' => $token,
'user_id' => $user->id
),
$log_in_url
);
//
$wp_new_user_notification_email['subject'] = 'Welcome on our website, please confirm your email';
$wp_new_user_notification_email['message'] = 'Blablabla... the url to confirm is: '. $url;
return $wp_new_user_notification_email;
}
6. Hook on the login page to check the $_GET, looking for user_id and token.
Here we check the token and the user. If everything is okay, update the user meta has_confirm_email to 1, so the user can connect, and add a message : "Your email has been confirmed, you can now log in"
add_action( 'login_init', 'custom_login_init');
function custom_login_init(){
if(!empty($_GET['token']) && !empty($_GET['user_id'])) {
if(get_the_author_meta( 'confirm_email_token', $_GET['user_id']) === $_GET['token']) {
// Set the has_confirm_email to 1 so the user can now log in
update_user_meta( $user_id, 'has_confirm_email', 1);
update_user_meta( $user_id, 'confirm_email_token', '');
echo 'Your email has been confirmed, you can now log in';
}
}
}
7. Time for thinking
Okay, after all of his, i'm gonna think a little, and read what i have tell you, to check if there is no mistake ^^. Tell me if you need more explanations.
I think this is a good start for you, and if you find the right hooks, you will achieve this rapidly.
Be careful on some hooks that i have used, because your theme may have use a custom registration or something.
Here is what I did:
added a column in the table wp_users to receive the email confirmation code
built a plugin (details here) called user-emails that allows me to bypass the first email sent upon registration by redefining the function wp_new_user_notification (in which I generate the confirmation code, add it to the user in the DB and send a confirmation email of my own sauce)
redefined the wp_authenticate function inside the same plugin user-emails to allow me to check if the email has been confirmed (column value not null)
created a page for the confirmation with the email and code passed to it that, in case of success, display a message and a link to the home page in order to login
finally got my hands on that one tiny line of code responsible for the auto login after registration located in the page user_auth.php inside the theme folder itself (that file also contains the layout for the login and registration form)
wp_set_auth_cookie( $user_id, true, $secure_cookie );
made sure to display a message after registration informing the user to check his email for the confirmation email

redirect user if not logged in

I am using customized pages on my site where I need to check that the user is logged in, and if not, redirect to another page.
On successful login, a session variable is set up as:
session_start();
$_SESSION['login'] = "1";
To check whether the user is logged in or not on a page, I use this code at the start of the page:
session_start();
if($_SESSION['login']=='')
{
#header("location:login.php");
}
However the page does not redirect even if the user is not logged in. The error shown is
Notice: Undefined index: login in XXXX/XXXX/XXXX/XXXX
Is there any other method to redirect users other than header(), or maybe some other code can be used to achieve the same purpose?
It appears the login index of $_SESSION is not set at the time you're checking it, most probably the $_SESSION['login'] = "1"; bit comes after your check, so you are going to have to make sure you verify whether it's set or not using the array_key_exists function as follows:
if (array_key_exists('login', $_SESSION) && $_SESSION['login']=='') {
#header("location:login.php");
}
Alternatively you may want to set explicitly $_SESSION['login'] = 0, for example, by default, and only set $_SESSION['login'] = "1"; if login is successful.
At the same time, I do not recommend you to use your own login mechanism, instead use scripts and techniques originally designed by knowledgeable coders of wordpress, and well tested by the community. One such approach is described in this question on the wordpress support site (add this to your theme's functions.php):
add_action( 'init', 'redirect_visitors' );
function redirect_visitors() {
if ( ! is_user_logged_in() ) {
wp_redirect( 'http://your-site.com/wp-login.php' );
exit;
}
}

Prevent Specific Email Registration Wordpress.org

So I'm looking for a way to prevent a specific email from registering an account on my website. It's a wordpress.org site.
I tried the Ban Hammer plugin, but it won't work.
I'm not looking for Comments, but for the site proper. Like a code I can put in functions.php or someplace and when this specific email is used to try and register an account on my site, to get an error.
Not an entire email domain, for example, #gmail.com. But a specific email, for example, stack#gmail.com.
Anyone knows how to do that?
EDIT: I found this tutorial here: http://www.davidtiong.com/block-spam-registrations-on-wordpress/
I tried adding this in Functions.php file right above the last ?> at the very bottom of the file:
function dtwd_blocked_emails($user_email) {
$dtwd_blocked_list = array("slojehupri#thrma.com", );
$user_email_split = explode('#', $user_email); $user_email_domain = $user_email_split[1];
if (in_array($user_email_domain, $dtwd_blocked_list)) {
//Return 1, for detection
return 1;
} else {
//Return 0 for no detection
return 0;
}
}
And I also added this in register.php of my theme:
elseif ( dtwd_blocked_emails( $user_email ) == 1) {
$errors->add( 'blocked_email', __( '<strong>ERROR</strong>: This email is not allowed.' ) );
}
And I added the same code in login.php of my theme.
And then I tried registering an account with this email (which should be blocked now): slojehupri#thrma.com
The site allowed me to register, and it allowed me to login. The email should've been blocked now and return an error when I try to register and/or login with it.
I'm not really sure how that function is supposed to work (it's not even hooked into anything...). I haven't tested this, but it sounds as simple as validating the email when the registration_errors filter hook is run. From the Codex:
The registration_errors filter hook filters the errors encountered when a new user is being registered. If any errors are present in $errors, this will abort the user's registration.
This sounds exactly like what you want to do (abort registration if the user email is in your blacklist). Again, this hasn't been tested, but I'd try something like the following in functions.php:
function so_32767928_blacklisted_user( $errors, $sanitized_user_login, $user_email ) {
// One or more blacklisted emails to validate against
$blacklist = array( 'slojehupri#thrma.com', );
// If the user trying to register is in the blacklist, add an error message
if ( in_array( $user_email, $blacklist ) ) {
$errors->add( 'blacklist_error', '<strong>ERROR</strong>: This email is not allowed to register on this site.' );
}
// Always return $errors, even if there are none
return $errors;
}
add_filter( 'registration_errors', 'so_32767928_blacklisted_user', 10, 3 );

check if user email exists, and if not, stop the submit of the ninja form

I've one form built with ninja forms, and I use ajax to send it.
I need to check if the email introduced already exists in database (user_email), and if it exists properly, I send the form properly, but if it doesn't exist, the form isn't submitted, and I need to give the user the message like "email does not exist".
The form is a survey to be completed by a registered user, who gives us a feedback about our services, but the survey is located in a page where the user can send its opinion without needed to be logged.
I'm investigating, and at the moment I have:
function example_disable_saving_subs( $save, $form_id ) {
global $ninja_forms_processing;
$form_id = $ninja_forms_processing->get_form_ID();
$email = ninja_forms_get_field_by_id( 18 );
//cuestionario feedback profesor sobre creación de un curso
if($form_id == 3){
if( !email_exists( $email )) {
$save = false;
$ninja_forms_processing->add_error('email_no_existe', 'El email no existe');
}
}
return $save;
}
add_filter( 'ninja_forms_save_submission', 'example_disable_saving_subs', 2, 10 );
But I pick up the field $email without value introduced...In addition, I don't know the way to give the user the message "email does not exists".
As you see, I chose the filter ninja_forms_save_submission. Maybe this is not the correct filter.
I hope your valious help.
Thanks in advance, Daniel
thanks for your help #Renato , I give you +1 :)
It's true that I can do it through the way you tell me, but I don't want to break the api of WordPress, that is, the way this cms uses javascript, php, etc etc...So, I wanted to do this through the API of ninja forms, which is the plugin I use for build this survey.
Finally, I solved it...it was my mistake, because I didn't use the correct filter...Investigating few more, there's another filter much more appropiate: ninja_forms_pre_process
Here is the code:
function add_change_ninja_forms_landing_page(){
add_action( 'ninja_forms_pre_process', 'handle_custom_ninja_forms' );
}
add_action( 'init', 'add_change_ninja_forms_landing_page' );
function handle_custom_ninja_forms(){
global $ninja_forms_processing;
$form_id = $ninja_forms_processing->get_form_ID();
//if it's my form of survey
if( $form_id == 3 ){
$email = $ninja_forms_processing->get_field_value( 18 ); //pick up the value of the email field
//use the native function of wordpress to check if there's a user with this email
//is anyone has this email, it does not exist
if( !email_exists( $email )) {
$ninja_forms_processing->add_error('email_no_existe', 'El email indicado no está registrado en nuestra base de datos'); //add_error stop the form and gives the error message
}
}
}
With the code above everything works fine! :)
Thanks!
Daniel,
I am not familiar with ninja_forms, but thinking of javascript, you can encapsulate your code to verify if users exists into an url and then, when making the ajax call, use it to verify...
If you can't change the ajax request, you can validate the field on it's blur event and disable the submit button untill it's marked as "successfull"
For you to create PHP files, and yet, use all Wordpress power and functionalities, you can simply include this file on the beggining of the file that will be called
require(wp-blog-header.php)

Resources