I can registration user without login using wp_insert_user? - wordpress

I use wp_insert_user to add a user, but there you need to have a username and password, and I only need mail without a username and password. Just use this function, because there is not a bad functionality, which I then need.
$user_company = $array_jsons['company'];
$user_email = $array_jsons['email'];
$role = $array_jsons['role'];
$info = array(
'user_login' => '', // how i do without login
'user__pass' => '', // how i do without login
'user_company' => $user_company,
'user_email' => $user_email,
'display_name' => $user_email,
'role' => $role
);
$result = wp_insert_user( $info );
if(is_wp_error( $result)) {
echo $result->get_error_message();
} else {
echo "Added user {$result}";
}

Please try to add the emails as username and password, because username and password are the mandatory fields
$user_company = $array_jsons['company'];
$user_email = $array_jsons['email'];
$role = $array_jsons['role'];
$info = array(
'user_login' => $user_email, // how i do without login
'user__pass' => $user_email, // how i do without login
'user_company' => $user_company,
'user_email' => $user_email,
'display_name' => $user_email,
'role' => $role
);
$result = wp_insert_user( $info );
if(is_wp_error( $result)) {
echo $result->get_error_message();
} else {
echo "Added user {$result}";
}

Related

Create Wordpress user when new custom post created

I want to create custom posts from frontend and backend. And while I create posts I want to create users. At frontend I use form and wp_insert_post so it creates post as I need. At backend I use this code:
add_action( 'publish_user_contact', 'custom_post_user_create', 1, 3);
function custom_post_user_create($post_id){
$user_login_id = 'user_'.random_int(100000, 999999);
update_post_meta($post_id, 'idr_contact_user_id', $user_login_id);
$password = wp_generate_password( 10, true, true );
if (!empty($_POST['contact_email'])){
$userdata = [
'user_login' => "$user_login_id",
'user_pass' => "$password",
'user_email' => $_POST['contact_email'],
'display_name' => sanitize_text_field( $_POST['contact_first_name'] .' '. $_POST['contact_last_name'] ),
'first_name' => sanitize_text_field( $_POST['contact_first_name'] ),
'last_name' => sanitize_text_field( $_POST['contact_last_name'] )
];
} else {
$userdata = [
'user_login' => "$user_login_id",
'user_pass' => "$password",
'display_name' => sanitize_text_field( $_POST['contact_first_name'] .' '. $_POST['contact_last_name'] ),
'first_name' => sanitize_text_field( $_POST['contact_first_name'] ),
'last_name' => sanitize_text_field( $_POST['contact_last_name'] )
];
}
$user_id = wp_insert_user( $userdata );
}
It creates user with custom post nut when I try to edit posts it creates more users. I tried to use new_to_publish, but it doesn't work (users don't creates). I tried to use save_post but it makes duplicates too.
How to prevent duplicates?
Try adding a check for the custom field, then the code won't be executed when editing a post.
add_action( 'publish_user_contact', 'custom_post_user_create', 1, 3);
function custom_post_user_create($post_id){
$user_login_id = 'user_'.random_int(100000, 999999);
if(get_post_meta($post_id, "idr_contact_user_id", true) ) {
return;
}
update_post_meta($post_id, 'idr_contact_user_id', $user_login_id);
$password = wp_generate_password( 10, true, true );
if (!empty($_POST['contact_email'])){
$userdata = [
'user_login' => "$user_login_id",
'user_pass' => "$password",
'user_email' => $_POST['contact_email'],
'display_name' => sanitize_text_field( $_POST['contact_first_name'] .' '. $_POST['contact_last_name'] ),
'first_name' => sanitize_text_field( $_POST['contact_first_name'] ),
'last_name' => sanitize_text_field( $_POST['contact_last_name'] )
];
} else {
$userdata = [
'user_login' => "$user_login_id",
'user_pass' => "$password",
'display_name' => sanitize_text_field( $_POST['contact_first_name'] .' '. $_POST['contact_last_name'] ),
'first_name' => sanitize_text_field( $_POST['contact_first_name'] ),
'last_name' => sanitize_text_field( $_POST['contact_last_name'] )
];
}
$user_id = wp_insert_user( $userdata );
}

Login WP - Connect single field to an external api

I made a plugin to allow wordpress login with external api.
Everything works, now what I have to do is that when a user logs in for the first time, the plugin checks to see if it is already present on wp, and where it was not already present, it creates a new user by taking behind username, email and password.
The new user is created but I would like it to bring with it also the id field from the external api saving it in an ACF field.
This is the code created so far:
function au_auth($user, $username, $password)
{
$options = get_option('au_options');
$endpoint = $options['au_apiurl'];
$user_email_key = 'email';
$password_key = 'password';
// Makes sure there is an endpoint set as well as username and password
if (!$endpoint || $user !== null || (empty($username) && empty($password))) {
return false;
}
// Check user exists locally
$user_exists = wp_authenticate_username_password(null, $username, $password);
if ($user_exists && $user_exists instanceof WP_User) {
$user = new WP_User($user_exists);
return $user;
}
// Build the POST request
$login_data = array(
$user_email_key => $username,
$password_key => $password
);
$auth_args = array(
'method' => 'POST',
'headers' => array(
'Content-type: application/x-www-form-urlencoded'
),
'sslverify' => false,
'body' => $login_data
);
$response = wp_remote_post($endpoint, $auth_args);
// Token if success; Not used right now
$response_token = json_decode($response['response']['token'], true);
$response_code = $response['response']['code'];
if ($response_code == 400) {
// User does not exist, send back an error message
$user = new WP_Error('denied', __("<strong>Error</strong>: Your username or password are incorrect."));
} else if ($response_code == 200) {
// External user exists, try to load the user info from the WordPress user table
$userobj = new WP_User();
// Does not return a WP_User object but a raw user object
$user = $userobj->get_data_by('email', $username);
if ($user && $user->ID) {
// Attempt to load the user with that ID
$user = new WP_User($user->ID);
}
} else {
// The user does not currently exist in the WordPress user table.
// Setup the minimum required user information
$userdata = array(
'user_email' => $username,
'user_login' => $username,
'user_pass' => $password
);
// A new user has been created
$new_user_id = wp_insert_user($userdata);
// Assign editor role to the new user (so he can access protected articles)
wp_update_user(
array(
'ID' => $new_user_id,
'role' => 'editor'
)
);
// Load the new user info
$user = new WP_User ($new_user_id);
}
}
// Useful for times when the external service is offline
remove_action('authenticate', 'wp_authenticate_username_password', 20);
return $user;
}
Anyone have any way how to help me?
Resolved! I hope this will help those who have found themselves in the same situation as me:
add_filter('authenticate', 'au_auth', 10, 3);
add_filter('register_new_user', 'au_registration', 10, 3);
// add_filter('profile_update', 'au_profile_update', 10, 3);
// add_filter('edit_user_profile_update', 'au_profile_edit', 10, 3);
function au_auth($user, $username, $password)
{
$options = get_option('au_options');
$endpoint = $options['au_apiurl'];
// Makes sure there is an endpoint set as well as username and password
if (!$endpoint || $user !== null || (empty($username) && empty($password))) {
return false;
}
$auth_args = [
'method' => 'POST',
'headers' => [
'Content-type: application/x-www-form-urlencoded',
],
'sslverify' => false,
'body' => [
'email' => $username,
'password' => $password,
],
];
$response = wp_remote_post($endpoint, $auth_args);
// Token if success; Not used right now
$response_token = json_decode($response['response']['token'], true);
$body = json_decode($response['body'], true);
$response_status_code = $response['response']['code'];
$success = $body !== 'KO';
if (!$success) {
// User does not exist, send back an error message
$user = new WP_Error('denied', __('<strong>Error</strong>: Your username
or password are incorrect.'));
} elseif ($success) {
$idExternal = $body['Id'];
$nome = $body['Name'];
$cognome = $body['Surname'];
$email = $body['Email'];
$userobj = new WP_User();
$user = $userobj->get_data_by('email', $email);
if ($user && $user->ID) {
$user = new WP_User($user->ID);
} else {
$userdata = [
'user_email' => $email,
'user_login' => join(' ', [$name, $surname]),
'user_pass' => '----',
];
$new_user_id = wp_insert_user($userdata);
$new_user_composite_id = 'user_' . $new_user_id;
update_field('field_60084ad3970a8', $idExternal, $new_user_composite_id);
update_field('field_5f22ca201c7b0', $name, $new_user_composite_id);
update_field('field_5f22ccd498f40', $surname, $new_user_composite_id);
update_field('field_5f22ce7b7c1db', $email, $new_user_composite_id);
$user = new WP_User($new_user_id);
}
}
remove_action('authenticate', 'wp_authenticate_username_password', 20);
return $user;
}

I want get_posts to return only posts of logged in user

Here's my code:
I'd like to only return posts of logged in user.
I am populating a dropdown form in WordPress gravity forms.
$current_user = _wp_get_current_user();
function populate_posts( $form) {
foreach ( $form['fields'] as &$field ) {
if ( $field->type != 'select' || strpos( $field->cssClass, 'populate-posts' ) === false ) {
continue;
}
$posts = get_posts( 'post_type=credit cards&numberposts=-1&post_status=publish&author=$current_user' );
$choices = array();
foreach ( $posts as $post ) {
$choices[] = array( 'text' => $post->post_title, 'value' => $post->post_title );
}
$field->placeholder = 'Select Credit Card';
$field->choices = $choices;
}
As i understand question of your's is to get "Post of Current User".Then here is a below code of it.
1) You need to pass author ID(Current User ID) as argument.
$current_user = wp_get_current_user();
$args = array(
'author' => $current_user->ID,
'orderby' => 'post_date',
'order' => 'ASC',
);
2) Pass above argument is post as below :
$current_user_posts = get_posts( $args );
I Hope this helps you.
You can also use WP_Query()
$user = wp_get_current_user();
$query_args = array(
'post_type' => 'post',
'author' => $user->ID,
);
$query = new WP_Query($query_args);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
$post = $query->post;
echo $post->post_title;
}
wp_reset_postdata();
}
else{
echo 'No posts found.';
}

Activate and Login user after registration Gravity Form

I wanted to automatically activate and login user after registration on my site using gravityform is there a way?
.I did some research and currently some of the guides are outdated.I tried this code,currently its not working
function autologin($user_id, $config, $entry, $password) {
wp_set_auth_cookie($user_id, false, '');
}
add_action("gform_user_registered", "autologin", 10, 4);
This checks if the user is logged in or not. If not, they will auto-login upon form submission.
/**
* Auto login after registration if not logged in.
*/
function ip_gravity_registration_autologin( $user_id, $user_config, $entry, $password ) {
// Only automatically login if we aren't *already* logged in
if ( ! is_user_logged_in() ) {
// Get the user data (for the login)
$user = get_userdata( $user_id );
// Sign the user in
wp_signon( array(
'user_login' => $user->user_login,
'user_password' => $password,
'remember' => false, // Don't set the remember cookie
));
}
}
add_action( 'gform_user_registered', 'ip_gravity_registration_autologin', 10, 4 );
Did you try this?
function pi_gravity_registration_autologin( $user_id, $user_config, $entry, $password ) {
$user = get_userdata( $user_id );
$user_login = $user->user_login;
$user_password = $password;
wp_signon( array(
'user_login' => $user_login,
'user_password' => $user_password,
'remember' => false
), false );
wp_set_current_user( $user_id, $user_login );
wp_set_auth_cookie( $user_id, true, false );
do_action( 'wp_login', $user_login );
}
Here's a modified version of the code from my Gravity Forms Auto Login plugin that handles this.
add_action( 'gform_user_registered', 'gw_auto_login', 10, 4 );
function gw_auto_login( $user_id, $feed, $entry, $password ) {
$user = new WP_User( $user_id );
$user_data = array(
'user_login' => $user->user_login,
'user_password' => $password,
'remember' => false
);
$result = wp_signon( $user_data );
if( ! is_wp_error( $result ) ) {
global $current_user;
$current_user = $result;
}
}
The plugin accounts for many other Gravity Forms scenarios that might interfere with automatically logging the user in.

Drupal: assign roles in user_save

I can't find a solution or right example for something that should be quite simple: assign a role to an user when creating it, this is what I'm trying:
$edit = array(
'name' => $_POST['name'],
'pass' => $password,
'mail' => $_POST['email'],
'status' => 0,
'language' => 'es',
'init' => $_POST['email'],
array(2 =>'authenticated', 4=>'my custom role') //as id and named in role db table
);
user_save(NULL, $edit);
The user is not being created, how can I do this?
Thank you
You haven't named the roles member as such. Try his modified version:
$edit = array(
'name' => $_POST['name'],
'pass' => $password,
'mail' => $_POST['email'],
'status' => 0,
'language' => 'es',
'init' => $_POST['email'],
'roles' => array(
2 => 'authenticated',
4 => 'my custom role',
),
);
user_save(NULL, $edit);
And you can use objects to do that.
// Check if user's email is unique
if (!user_load_by_mail($_POST['email'])) {
$account = new stdClass;
$account->name = $_POST['name'];
$account->pass = user_hash_password($password);
$account->mail = $_POST['email'];
$account->status = FALSE;
$account->language = 'es';
$account->init = $_POST['email'];
$account->roles = array(
DRUPAL_AUTHENTICATED_RID => TRUE,
'Your custom role' => TRUE,
);
user_save($account);
}
Here is a hook I've written to add a role to a user when a new user is inserted:
<?php
function MYMODULE_user_insert(&$edit, $account, $category){
if (array_key_exists('profile_1', $account)) {
$is_university = FALSE;
if ($account->profile_sport_club['field_club']['und'][0]['value'] == 1 ) {
$is_university = TRUE;
}
if ($is_university) {
$uid = $account->uid;
$role_name = 'uni_club';
if ($role = user_role_load_by_name($role_name)) {
user_multiple_role_edit(array($uid), 'add_role', $role->rid);
}
}
}
}
?>
Thanks to this tip, it's now much simpler.
function first_user_insert(&$edit, $account, $category, $node){
$uid = $account->uid;
$role_name = 'role name';
if ($role = user_role_load_by_name($role_name)) {
user_multiple_role_edit(array($uid), 'add_role', $role->rid);
}
}

Resources