WooCommerce - register second user in woocommerce_created_customer hook - wordpress

I'm coming across an issue when trying to register a second user account once someone registers as a customer via WooCommerce. I have added the following woocommerce_created_customer hook:
add_action('woocommerce_created_customer', function($customer_id)
{
if(isset($_POST['second_user_first_name']) && isset($_POST['second_user_last_name']))
{
$createSecondUserId = wp_create_user(strtolower($_POST['second_user_first_name'].'-'.$_POST['second_user_last_name']).'-'.$customer_id, wp_generate_password(), 'test#test.com');
if(is_wp_error($createSecondUserId))
{
$errors = $createSecondUserId->errors;
print_r($errors);
die();
}
}
});
However I get the following error when submitting a new WooCommerce registration:
Array ( [existing_user_login] => Array ( [0] => Sorry, that username already exists! ) )
It's strange as I'm setting a random username within the wp_create_user function, so the usernames should not clash. Has anyone got any ideas?

You can use username_exists() to determines that the given username exists.
add_action( 'woocommerce_created_customer', function($customer_id){
if( isset( $_POST['second_user_first_name'] ) && isset( $_POST['second_user_last_name'] ) ) {
if( !username_exists( strtolower( $_POST['second_user_first_name'].'-'.$_POST['second_user_last_name'] ).'-'.$customer_id ) ){
$createSecondUserId = wp_create_user( strtolower( $_POST['second_user_first_name'].'-'.$_POST['second_user_last_name'] ).'-'.$customer_id, wp_generate_password(), 'test#test.com' );
if(is_wp_error($createSecondUserId)){
$errors = $createSecondUserId->errors;
print_r($errors);
die();
}
}
}
});

If the username already exists you can create a new one by adding a progressive numeric suffix. In this way you will be sure that the username of the second account will always be unique.
Note that if you run multiple tests with your current code you need to
make sure you remove the user with the email address test#test.com
otherwise you will get an error: [existing_user_email] => Sorry, that email address is already used!.
add_action('woocommerce_created_customer', function( $customer_id ) {
if ( isset($_POST['second_user_first_name']) && isset($_POST['second_user_last_name']) ) {
// create the username based on the form data
$username = strtolower( $_POST['second_user_first_name'] . '-' . $_POST['second_user_last_name'] ) . '-' . $customer_id;
// if the username already exists it creates a unique one
if ( username_exists($username) ) {
$i = 0;
while ( username_exists($username) ) {
$username = $username . '-' . ++$i;
}
}
// create the second user
$createSecondUserId = wp_create_user( $username, wp_generate_password(), 'test#test.com' );
}
});
The code has been tested and works. Add it to your active theme's functions.php.

Related

Pre fill Woocommerce Reset Password field with URL parameter

I am trying to send out emails to my customers and allow them one click to reset passwords with their email pre-filled on the reset password page by URL /account/lost-password/?email=123#gmail.com
However, I am not sure how to make it right. Here is my code. Thanks!
add_action( 'template_redirect', 'set_custom_data_wc_session' );
function set_custom_data_wc_session () {
if ( isset( $_GET['email'] ) ) {
$em = isset( $_GET['email'] ) ? esc_attr( $_GET['email'] ) : '';
// Set the session data
WC()->session->set( 'custom_data', array( 'email' => $em ) );
}
}
add_filter( 'woocommerce_login_form' , 'prefill_login_form' );
function prefill_login_form ( $fields ) {
// Get the session data
$data = WC()->session->get('custom_data');
// Email
if( isset($data['email']) && ! empty($data['email']) )
$fields['user_login']['default'] = $data['email'];
return $fields;
}
I managed to do it by referencing this thread
Pre-fill Woocommerce login fields with URL variables saved in session
<?php
add_action('woocommerce_lostpassword_form','woocommerce_js_2');
function woocommerce_js_2()
{ // break out of php
?>
<script>
// Setup a document ready to run on initial load
jQuery(document).ready(function($) {
//var r = /[?|&](\w+)=(\w+)+/g; //matches against a kv pair a=b
var r = /[?|&](\w+)=([\w.-]+#[\w.-]+)/g;
var query = r.exec(window.location.href); //gets the first query from the url
while (query != null) {
//index 0=whole match, index 1=first group(key) index 2=second group(value)
$("input[name="+ query[1] +"]").attr("value",query[2]);
query = r.exec(window.location.href); //repeats to get next capture
}
});
</script>
<?php } // break back into php

Disable password change option for specific user

How can I disable the password change option for specific user in Wordpress?
I have a user where I set a new password each week for multiple users. But some tried to change the password for this user. I don't want that - but only for this specific user profile. All the other users should be able toi change their password.
I have tried different plugins but none of them work.
Thanks a lot if you can help on this!
Add this in your function.php file
class Password_Reset_Removed
{
function __construct()
{
add_filter( 'show_password_fields', array( $this, 'disable' ) );
add_filter( 'allow_password_reset', array( $this, 'disable' ) );
}
function disable()
{
if ( is_admin() ) {
$userdata = wp_get_current_user();
$user = new WP_User($userdata->ID);
if ( !empty( $user->roles ) && is_array( $user->roles ) && $user->roles[0] == 'administrator' )
return true;
}
return false;
}
}
$pass_reset_removed = new Password_Reset_Removed();
We have just removed the fields to change password from the back-end of the WordPress. Now, some users will also try to reset the password using the Lost your password? form from the log-in page.
In order to prevent them from doing that, we will remove lost password link and disable the lost password form by adding below code
function remove_lost_your_password($text)
{
return str_replace( array('Lost your password?', 'Lost your password'), '', trim($text, '?') );
}
add_filter( 'gettext', 'remove_lost_your_password' );
function disable_reset_lost_password()
{
return false;
}
add_filter( 'allow_password_reset', 'disable_reset_lost_password');
Note - you can update userid - as per your requirements

Conditionally change upload directory on XMLRPC call according to username

I've searched seemingly every relevant question on this but I'm stuck, as none of them address the particular case of uploads through XML RPC.
I want to conditionally change the Wordpress file upload directory, only if the file is coming in through an XML RPC call and only if the call is coming in from a particular user.
My approach is based on a combination of this Answer, this Answer and the Codex.
Here's what I tried with no luck:
add_filter( 'xmlrpc_methods', 'call_intercept1' );
function call_intercept1( $methods ) {
$methods[ 'metaWeblog.newMediaObject' ] = 'custom_upload1';
return $methods;}
function custom_upload1( $args ) {
global $wpdb;
$username = $this->escape( $args[1] );
$password = $this->escape( $args[2] );
$data = $args[3];
$name = sanitize_file_name( $data['name'] );
$type = $data['type'];
$bits = $data['bits'];
if ( !$user = $this->login($username, $password) )
return $this->error;
if ( $username = "XXX" ) {
add_filter('upload_dir', 'custom_upload_dir1');
}
$upload = wp_upload_bits($name, null, $bits);
if ( ! empty($upload['error']) ) {
/* translators: 1: file name, 2: error message */
$errorString = sprintf( __( 'Could not write file %1$s (%2$s).' ), $name, $upload['error'] );
return new IXR_Error( 500, $errorString );
}
return $upload;
}
function custom_upload_dir1( $param ){
$custom_dir = '/the-desired-directory';
$param['path'] = $param['path'] . $custom_dir;
$param['url'] = $param['url'] . $custom_dir;
error_log("path={$param['path']}");
error_log("url={$param['url']}");
error_log("subdir={$param['subdir']}");
error_log("basedir={$param['basedir']}");
error_log("baseurl={$param['baseurl']}");
error_log("error={$param['error']}");
return $param;
}
The file is being uploaded correctly, but the conditional directory change isn't happening.
Does someone know why that would be?
I was able to get this worked out, essentially using Ulf B's Custom Upload Dir as a model and simplifying it from there.
For anyone else facing the same problem, here's what works:
// XMLRPC Conditional Upload Directory
add_action('xmlrpc_call', 'redirect_xmlrpc_call');
function redirect_xmlrpc_call($call){
if($call !== 'metaWeblog.newMediaObject'){return;}
global $wp_xmlrpc_server;
$username = $wp_xmlrpc_server->message->params[1];
$data = $wp_xmlrpc_server->message->params[3];
if($username !== "XXX"){return;}
else {custom_pre_upload($data);}}
function custom_pre_upload($data){
add_filter('upload_dir', 'custom_upload_dir');
return $data;}
function custom_post_upload($fileinfo){
remove_filter('upload_dir', 'custom_upload_dir');
return $fileinfo;}
function custom_upload_dir($path){
if(!empty($path['error'])) { return $path; } //error; do nothing.
$customdir = '/' . 'your-directory-name';
$path['subdir'] = $customdir;
$path['path'] .= $customdir;
$path['url'] .= $customdir;
return $path;}

after setup theme action creating issue with nonce in wordpress 4.3.1

I am using add_action( 'after_setup_theme', 'custom_login' ); hook in one of my website for auto redirect user to his dashboard page.
Here is my code :---
function custom_login($username, $password='') {
$creds = array();
$creds['user_login'] = $username;
$creds['user_password'] = $password;
$creds['remember'] = true;
$user = wp_signon( $creds, false );
if ( is_wp_error($user) ){
echo $user->get_error_message();
}
}
// run it before the headers and cookies are sent
add_action( 'after_setup_theme', 'custom_login' );
Its working fine on old version, But now I have upgrade wordpress version and its creating problem with nonce.
Are you sure you want to do this?
Everytime this error display on the screen when I do anything like update plugin, theme and permalinks.
When I comment this code then website working fine except auto redirect functionality.
Here is my website url :- https://www.linearrecruitment.co.uk/
Please help me where I do mistake.
That's a normal behaviour - nonce is a token used by Wordpress to check the validity of the form in order to prevent CSRF attacks.
A valid login form in Wordpress should have an hidden input field generated with wp_nonce_field:
wp_nonce_field('my_login_form');
Then in the login function the token is checked with the wp_verify_nonce function:
if (!isset($_POST['my_login_form']) || !wp_verify_nonce($_POST['_wpnonce'], 'my_login_form')) {
die('Invalid form');
}
What you're trying to do (auto login) is done wrong as add_action doesn't send any parameter for the after_setup_theme hook, so your username is probably empty. I don't know how this could possibly work before, maybe it managed to log in somehow with an empty username.
I suggest you to declare some globals vars for your username and password, as it seems to be static inputs:
global $username, $password;
$username = 'my_login';
$password = 'my_password';
And then on the beginning of your function import those globals with:
global $username, $password;
So what about the nonce?
On the last versions of Wordpress, the check_admin_referer have changed a bit, from:
function check_admin_referer( $action = -1, $query_arg = '_wpnonce' ) {
if ( -1 == $action )
_doing_it_wrong( __FUNCTION__, __( 'You should specify a nonce action to be verified by using the first parameter.' ), '3.2' );
$adminurl = strtolower(admin_url());
$referer = strtolower(wp_get_referer());
$result = isset($_REQUEST[$query_arg]) ? wp_verify_nonce($_REQUEST[$query_arg], $action) : false;
if ( !$result && !(-1 == $action && strpos($referer, $adminurl) === 0) ) {
wp_nonce_ays($action);
die();
}
do_action( 'check_admin_referer', $action, $result );
return $result;
}
To :
function check_admin_referer( $action = -1, $query_arg = '_wpnonce' ) {
if ( -1 == $action )
_doing_it_wrong( __FUNCTION__, __( 'You should specify a nonce action to be verified by using the first parameter.' ), '3.2' );
$adminurl = strtolower(admin_url());
$referer = strtolower(wp_get_referer());
$result = isset($_REQUEST[$query_arg]) ? wp_verify_nonce($_REQUEST[$query_arg], $action) : false;
do_action( 'check_admin_referer', $action, $result );
if ( ! $result && ! ( -1 == $action && strpos( $referer, $adminurl ) === 0 ) ) {
wp_nonce_ays( $action );
die();
}
return $result;
}
As you can see they moved the check_admin_referer hook - now we can change the value of $result before the wp_nonce_ays function (the one that display the message you try to get rid of) as been called.
That mean we could add the following hook in the theme functions.php in order to force the nonce validation:
add_action( 'check_admin_referer', array('custom_check_admin_referer' ) );
function custom_check_admin_referer() {
return 1;
}
That should work around your problem, but you must be aware that this could possibly be a security issue - you maybe want to do more test in that function before returning 1.

How to custom user url in BuddyPress and WordPress?

Thanks for support!
I need to custom user url in my page using WordPress and BuddyPress.
This is example:
From: (current)
http://example.com/user/pum_su411
To
http://example.com/user/548234
With 548234 is ID of the user.
I want after completed the custom, all users will have url like above automatically.
Thanks for all solutions!
add this code to your theme functions.php file.
function _bp_core_get_user_domain($domain, $user_id, $user_nicename = false, $user_login = false) {
if ( empty( $user_id ) ){
return;
}
if( isset($user_nicename) ){
$user_nicename = bp_core_get_username($user_id);
}
$after_domain = bp_get_members_root_slug() . '/' . $user_id;
$domain = trailingslashit( bp_get_root_domain() . '/' . $after_domain );
$domain = apply_filters( 'bp_core_get_user_domain_pre_cache', $domain, $user_id, $user_nicename, $user_login );
if ( !empty( $domain ) ) {
wp_cache_set( 'bp_user_domain_' . $user_id, $domain, 'bp' );
}
return $domain;
}
add_filter('bp_core_get_user_domain', '_bp_core_get_user_domain', 10, 4);
function _bp_core_get_userid($userid, $username){
if(is_numeric($username)){
$aux = get_userdata( $username );
if( get_userdata( $username ) )
$userid = $username;
}
return $userid;
}
add_filter('bp_core_get_userid', '_bp_core_get_userid', 10, 2);
function _bp_get_activity_parent_content($content){
global $bp;
$user = get_user_by('slug', $bp->displayed_user->fullname); // 'slug' - user_nicename
return preg_replace('/href=\"(.*?)\"/is', 'href="'.bp_core_get_user_domain($user->ID, $bp->displayed_user->fullname).'"', $content);
}
add_filter( 'bp_get_activity_parent_content','_bp_get_activity_parent_content', 10, 1 );
function _bp_get_activity_action_pre_meta($content){
global $bp;
$fullname = $bp->displayed_user->fullname; // 'slug' - user_nicename
$user = get_user_by('slug', $fullname);
if(!is_numeric($user->ID) || empty($fullname)){
$args = explode(' ', trim(strip_tags($content)));
$fullname = trim($args[0]);
$user = get_user_by('slug', $fullname);
}
return preg_replace('/href=\"(.*?)\"/is', 'href="'.bp_core_get_user_domain($user->ID, $fullname).'"', $content);
}
add_action('bp_get_activity_action_pre_meta', '_bp_get_activity_action_pre_meta');
add_filter('bp_core_get_userid_from_nicename', '_bp_core_get_userid', 10, 2);
Just spent a bit of time going over the documentation, codex and files of BuddyPress and i can find ways of changing the /user/ part of the url but sadly not the /username side of it.
Reading through, it is controlled within the core of BuddyPress and any changes to the core can cause crashes and more than likely to cause problems or overwrites further down the line.
This isn't to say it's not possible though, it is most certainly possible, but it will require a great deal of editing to many many different files, an edit to a number of BuddyPress functions and there are no guarantee's on it working straight out or even working further down the line when files get update.
I would recommend going onto the BuddyPress Trac and putting in a ticket to have the feature added to change user url structure. It would be a cool feature to be able to swap between a username, full name, ID or any other unique identifiable string.
You can access it here: https://buddypress.trac.wordpress.org/
Alternatively, you can try what aSeptik has done above, but make sure to update that file with any changes when BuddyPress updates as well.

Resources