logged-in user’s information in contact for 7 plugin - wordpress

I have 2 users in WordPress. One is admin and another is a contributor.
I am trying to send email using the contact form 7 plugin.
I logged in by contributor user. I need to send user (contributor) details like email. I use a code default:user_display_name and [email* your-email default:user_email] in message body field. Both of them are not useful.
If I use [_site_admin_email] email of admin is sent. I want to send the logged-in user email.

You should use wpcf7_before_send_mail action hook to add user's info in your email body. Below is an example on how you can do that.
add_action( 'wpcf7_before_send_mail', 'wpcf7_add_text_to_mail_body' );
function wpcf7_add_text_to_mail_body($contact_form){
$form_id = $contact_form->posted_data['_wpcf7']; // Get for ID
if ($form_id == 123): // 123 => Your Form ID.
$current_user = wp_get_current_user(); // Get Current User Object
$user_email = $current_user->user_email;
// get mail property
$mail = $contact_form->prop( 'mail' ); // returns array
// add content to email body
$mail['body'] .= 'User Email Address: ';
$mail['body'] .= $user_email;
// set mail property with changed value(s)
$contact_form->set_properties( array( 'mail' => $mail ) );
endif;
}

Related

How to get contact email from submitted data in Contact Form 7?

I would like to subscribe the user to my other newsletter system using Contact Form 7. I tried to get the recipient email from the submitted form with the below code, but it returns sender (admin) email.
add_action('wpcf7_before_send_mail', function ($contact_form) {
$mailProp = $contact_form->get_properties('mail');
subscribe_to_another_newsletter($mailProp['mail']['recipient']);
});
How can I get the contact's data?
You want to grab your submission and then use the form field you used for email to do what you want with it.
add_action( 'wpcf7_before_send_mail', array($this, 'cf7_process_form'));
function my_cf7_process_form(){
// This calls the static get the cf7 form data
$submission = WPCF7_Submission::get_instance();
if ( $submission ) {
// $posted_data = array with all form fields
$posted_data = $submission->get_posted_data();
}
// if [your-email] is the form tag
$email = $posted_data['your-email'];
subscribe_to_another_newsletter($email);
}

Store contactform 7 data in to Users - wordpress

I'm working on the WordPress website where I want to create the registration form with contact form 7 plugin, users details are stored in the database but unable login to with details which are stored by the contact form 7 plugin into the database?
Any idea how can user login with details which are stored by the contact form 7 plugin?
Contact Form 7 Form Example
<label>Email (required)
[text* your-email] </label>
<label>Phone(required)
[text* your-phone] </label>
<label>Password(required)
[password* pass] </label>
Error
ERROR: The password you entered for the email address test#yahoo.com
is incorrect. Lost your password?
You need to add the code in wpcf7_before_send_mail hook, please have a look at below completed working code.
add_action('wpcf7_before_send_mail', 'save_form' );
function save_form( $wpcf7 ) {
global $wpdb;
/*
Note: since version 3.9 Contact Form 7 has removed $wpcf7->posted_data
and now we use an API to get the posted data.
*/
$submission = WPCF7_Submission::get_instance();
if ( $submission ) {
$submited = array();
$submited['posted_data'] = $submission->get_posted_data();
}
$email=$submited['posted_data']['your-email'];
$pass=$submited['posted_data']['pass'];
$userdata = array(
'user_login' => $email,
'user_email' => $email,
'user_pass' => $pass // When creating an user, `user_pass` is expected.
);
$user_id = wp_insert_user( $userdata ) ;
}

How Can I add Email Verification Functions For WooCommerce

I would like to add Email verification procedure when user registers in WooCommerce. WordPress then emails a verification link to user's email. If link is clicked, it then activates the user's account. How would I do that?
I have used the code provided by Amit Kayshap and refined it to include extra checks and functions like automatically logging a user in after their account has been activated, resulting in a much smoother user experience.
Update: Unlike the original code, this one will not require any existing user to confirm their email address as well.
Like the code I based it upon, it is designed to run on a WordPress installation running WooCommerce. It also works if you have disabled the standard WordPress registration page.
You'll need an empty page with the URL yoursite.com/verify/ that builds on a template that contains <?php wc_print_notices(); ?> within its content container. It'll replace the /sign-in/ destination from the original code and will handle almost all messages created by this code.
Next, add this code to your theme's functions.php:
function wc_registration_redirect( $redirect_to ) { // prevents the user from logging in automatically after registering their account
wp_logout();
wp_redirect( '/verify/?n=1'); // redirects to a confirmation message
exit;
}
function wp_authenticate_user( $userdata ) { // when the user logs in, checks whether their email is verified
$has_activation_status = get_user_meta($userdata->ID, 'is_activated', false);
if ($has_activation_status) { // checks if this is an older account without activation status; skips the rest of the function if it is
$isActivated = get_user_meta($userdata->ID, 'is_activated', true);
if ( !$isActivated ) {
my_user_register( $userdata->ID ); // resends the activation mail if the account is not activated
$userdata = new WP_Error(
'my_theme_confirmation_error',
__( '<strong>Error:</strong> Your account has to be activated before you can login. Please click the link in the activation email that has been sent to you.<br /> If you do not receive the activation email within a few minutes, check your spam folder or click here to resend it.' )
);
}
}
return $userdata;
}
function my_user_register($user_id) { // when a user registers, sends them an email to verify their account
$user_info = get_userdata($user_id); // gets user data
$code = md5(time()); // creates md5 code to verify later
$string = array('id'=>$user_id, 'code'=>$code); // makes it into a code to send it to user via email
update_user_meta($user_id, 'is_activated', 0); // creates activation code and activation status in the database
update_user_meta($user_id, 'activationcode', $code);
$url = get_site_url(). '/verify/?p=' .base64_encode( serialize($string)); // creates the activation url
$html = ( 'Please click here to verify your email address and complete the registration process.' ); // This is the html template for your email message body
wc_mail($user_info->user_email, __( 'Activate your Account' ), $html); // sends the email to the user
}
function my_init(){ // handles all this verification stuff
if(isset($_GET['p'])){ // If accessed via an authentification link
$data = unserialize(base64_decode($_GET['p']));
$code = get_user_meta($data['id'], 'activationcode', true);
$isActivated = get_user_meta($data['id'], 'is_activated', true); // checks if the account has already been activated. We're doing this to prevent someone from logging in with an outdated confirmation link
if( $isActivated ) { // generates an error message if the account was already active
wc_add_notice( __( 'This account has already been activated. Please log in with your username and password.' ), 'error' );
}
else {
if($code == $data['code']){ // checks whether the decoded code given is the same as the one in the data base
update_user_meta($data['id'], 'is_activated', 1); // updates the database upon successful activation
$user_id = $data['id']; // logs the user in
$user = get_user_by( 'id', $user_id );
if( $user ) {
wp_set_current_user( $user_id, $user->user_login );
wp_set_auth_cookie( $user_id );
do_action( 'wp_login', $user->user_login, $user );
}
wc_add_notice( __( '<strong>Success:</strong> Your account has been activated! You have been logged in and can now use the site to its full extent.' ), 'notice' );
} else {
wc_add_notice( __( '<strong>Error:</strong> Account activation failed. Please try again in a few minutes or resend the activation email.<br />Please note that any activation links previously sent lose their validity as soon as a new activation email gets sent.<br />If the verification fails repeatedly, please contact our administrator.' ), 'error' );
}
}
}
if(isset($_GET['u'])){ // If resending confirmation mail
my_user_register($_GET['u']);
wc_add_notice( __( 'Your activation email has been resent. Please check your email and your spam folder.' ), 'notice' );
}
if(isset($_GET['n'])){ // If account has been freshly created
wc_add_notice( __( 'Thank you for creating your account. You will need to confirm your email address in order to activate your account. An email containing the activation link has been sent to your email address. If the email does not arrive within a few minutes, check your spam folder.' ), 'notice' );
}
}
// the hooks to make it all work
add_action( 'init', 'my_init' );
add_filter('woocommerce_registration_redirect', 'wc_registration_redirect');
add_filter('wp_authenticate_user', 'wp_authenticate_user',10,2);
add_action('user_register', 'my_user_register',10,2);
If you are running a multilingual site, you can make the code translation-ready very easily. Just change the text strings like this: __( 'Text you want to translate', 'your-theme' ) This allows translation plugins like WPML to add the string to a translation table in the your-theme text domain.
Note that any string containing a variable like .$url. will generate a new string every time a different user activates its function. To circumvent this (and prevent string spamming into your database), we can translate them directly in the code:
if(ICL_LANGUAGE_CODE=='de'){
wc_add_notice( __( 'German error message' ), 'error' );
} else {
wc_add_notice( __( 'English error message' ), 'error' );
}
In this example, the german message will be output if the user's language code is detected as de (Also works if it is a variation like de_DE_formal), else it will output the english message.
Edit: I updated the code to not require an existing user to retroactively confirm their email address.

Link login of two completely separate wordpress websites

I have two wordpress websites running on sub-domain of a server like http://first.mywebsites.net and http://second.mywebsites.net
They both are just like private sites, I can see the content of pages if I am logged in to the website otherwise redirected to the login page.
Now what I want is, if I am log in my first website and go to the link of second website in same browser then I am able to see the content of pages as a logged in user.
This must be happen only in a case when the user which is logged in first website having the same user(user registered with same mail id) in database of second website. As in case of my website, mostly users are registered with same mail id in both the websites.
Trying to achieve this by two approaches but still unable to get this by any of them :
Approach 1 : Adding a table to second website and save the user email and a auth key. Using curl to fetch the details and then logged in. This Approach is as mentioned in here : http://carlofontanos.com/auto-login-to-wordpress-from-another-website
But as I have mentioned it previous, that both the website is in my case are having private content, so in this case I am unable to fetch the details using curl. My code for curl is like :
$api_url = "http://second.mywebsites.net/autologin-api/";
// If you are using WordPress on website A, you can do the following to get the currently logged in user:
global $current_user;
$user_email = $current_user->user_email;
// Set the parameters
$params = array(
'action' => 'get_login_key', // The name of the action on Website B
'key' => '54321', // The key that was set on Website B for authentication purposes.
'user_email' => $user_email // Pass the user_email of the currently logged in user in Website A
);
// Send the data using cURL
$ch = curl_init($api_url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$gbi_response = curl_exec($ch);
curl_close($ch);
// Parse the response
parse_str($gbi_response);
print_r($gbi_response);
In this case I am not getting the response, My page redirect me to the login page of second website.
Approach 2 : Trying to do it with the use of cookies as I want to logged in to second website in same browser.
I have added a new cookie in my first website like :
global $current_user;
$user_email = $current_user->user_email;
if($user_email != ''){
$_COOKIE['current_user_mail_id'] = $user_email;
}
echo "<pre>";
print_r($_COOKIE);
echo "</pre>";
and added cookie is showing with the other cookies. But when I am checking this in my second website on same browser like :
echo "<pre>";
print_r($_COOKIE);
echo "</pre>";
The cookie which I have added in my first website is not showing on my second website.
I am not much familiar with cookies, setting auth cookies etc.
Please suggest a solution, how can I achieve this.
You can accomplished by using "Single Signon".
Instruction-
To simplify passing users between our systems I have created this PHP class
that you are welcome to use.
To check if a user is signed in:
$signon = new SingleSignon();
$userId = $signon->checkCookie();
if($userId){
// user is logged in and this is their id
}
else{
// user is not logged in or they are exipred
}
If the user is not logged in then use our api to login then use the following code if the api call is successful.
To set a user as logged in:
$signon = new SingleSignon();
$signon->setCookie($userId);
NOTE: You need to be using ssl for the cookie to be read.
I have gone through the solution provided by Gaurav and find a idea to make this possible for wordpress websites.
Place below mentioned code at the place where you want to put the link to go to your second website :
<?php global $current_user;
$user_email = $current_user->user_email;
$user_login = $current_user->user_login;
if($user_email != ''){
$email_encoded = rtrim(strtr(base64_encode($user_email), '+/', '-_'), '=');
$user_login_encoded = rtrim(strtr(base64_encode($user_login), '+/', '-_'), '=');
echo '<div class="dtNode">Link to second website</div>';
}?>
Now prepare a sso.php file and place it to the root installation of your second site where you want to logged in automatically. Now put the below code there :
<?php
require_once( 'wp-load.php' ); //put correct absolute path for this file
global $wpdb;
if(isset($_GET['key']) && !empty($_GET['key'])){
$email_decoded = base64_decode(strtr($_GET['key'], '-_', '+/'));
$username_decoded = base64_decode(strtr($_GET['detail'], '-_', '+/'));
$received_email = sanitize_text_field($email_decoded);
$received_username = sanitize_text_field($username_decoded);
if( email_exists( $received_email )) {
//get the user id for the user record exists for received email from database
$user_id = $wpdb->get_var($wpdb->prepare("SELECT * FROM wp_users WHERE user_email = %s", $received_email ) );
wp_set_auth_cookie( $user_id); //login the user
wp_redirect( 'http://second.mywebsites.net');
}else {
//register those user whose mail id does not exists in database
if(username_exists( $received_username )){
//if username coming from first site exists in our database for any other user,
//then the email id will be set as username
$userdata = array(
'user_login' => $received_email,
'user_email' => $received_email,
'user_pass' => $received_username, // password will be username always
'first_name' => $received_username, // first name willl be username
'role' => 'subscriber' //register the user with subscriber role only
);
}else {
$userdata = array(
'user_login' => $received_username,
'user_email' => $received_email,
'user_pass' => $received_username, // password will be username always
'first_name' => $received_username, // first name willl be username
'role' => 'subscriber' //register the user with subscriber role only
);
}
$user_id = wp_insert_user( $userdata ) ; // adding user to the database
//On success
if ( ! is_wp_error( $user_id ) ) {
wp_set_auth_cookie( $user_id); //login that newly created user
wp_redirect( 'http://second.mywebsites.net');
}else{
echo "There may be a mismatch of email/username with the existing record.
Check the users with your current email/username or try with any other account.";die;
}
}
die;
} ?>
Above code works for me, you can modify the code as per your needs. For more clear explanation, you can check here : http://www.wptricks24.com/auto-login-one-website-another-wordpress

Access User Meta Data on User Registration in Wordpress

I am attempting to carry out a few functions when a user registers on a wordpress site. I have created a module for this which carries out the following function:
add_action( 'user_register', 'tml_new_user_registered' );
function tml_new_user_registered( $user_id ) {
//wp_set_auth_cookie( $user_id, false, is_ssl() );
//wp_redirect( admin_url( 'profile.php' ) );
$user_info = get_userdata($user_id);
$subscription_value = get_user_meta( $user_id, "subscribe_to_newsletter", TRUE);
if($subscription_value == "Yes") {
//include("Subscriber.Add.php");
}
echo "<pre>: ";
print_r($user_info);
print_r($subscription_value);
echo "</pre>";
exit;
}
But it seems that i am not able to access any user meta data as at the end of this stage none of it is stored.
Any ideas how i execute a function once Wordpress has completed the whole registration process of adding meta data into the relevant tables too?
I attempted to use this:
add_filter('user_register ','tml_new_user_registered',99);
But with no luck unfortunately.
Thanks in advance!
I read at the action reference api page that the user id is passed as user ID. Try substituting your $user_id for $user_ID.
I don't think the user metadata is available at the point where this action hook is triggered. From the Codex
"Not all user meta data has been stored in the database when this action is triggered. For example, nickname is in the database but first_name and last_name are not (as of 3.9.1). The password has already been encrypted when this action is triggered."

Resources