Update User Meta after Registration - php

In wordpress, after a user registers, I am using the function below to create two pages of two different custom post types, and I then need to store a custom meta value in their user data to assist with redirects later. I've found that if I specify custom meta values during registration (on registration form), I can retrieve these values later with :
global $current_user;
get_currentuserinfo();
$theirRedirectKey = $current_user->rpr_redirect_key;
However, in the following functions.php snippet, I can't the meta value to save for retrieval later.
function after_registration($user_id){
// Get the Newly Created User ID
$the_user = get_userdata($user_id);
// Get the Newly Created User Name
$new_user_name = $the_user->user_login;
// Create a unique Tour Code Prefix from User ID
$tourPrefix = $the_user->ID;
// Check for Tour Code Key if entered into registration form
$enteredKey = $the_user->rpr_redirect_key;
if($enteredKey == ''){
//Create the first Tour Builder Page
$tourBuilder = array();
$tourBuilder['post_title'] = $new_user_name . '| Custom Educational Tour';
// Next line may not be important after hubpages are set up.
$tourBuilder['post_name'] = 'builder-' . $tourPrefix;
$tourBuilder['post_type'] = 'builder';
$tourBuilder['post_content'] = 'This is the content!';
$tourBuilder['post_author'] = $user_id;
$tourBuilder['post_status'] = 'publish';
$tour_id = wp_insert_post( $tourBuilder );
// Build hubpage
$hubpage = array();
$hubpage['post_title'] = $new_user_name . '\'s Hubpage';
// URL must be unique
$hubpage['post_name'] = $new_user_name;
$hubpage['post_type'] = 'hubpages';
$hubpage['post_author'] = $user_id;
$hubpage['post_status'] = 'publish';
$hub_id = wp_insert_post( $hubpage );
//Update User with proper redirect keys for some reason this line doesn't work.
add_user_meta($the_user, 'rpr_redirect_key', '/hubpage/' . $new_user_name, true);
}
}
add_action('user_register', 'after_registration');
Help would be much appreciated.

In the line
add_user_meta( $the_user, 'rpr_redirect_key', '/hubpage/' . $new_user_name, true);
$the_user isn't the ID. Try $the_user->ID or $user_id instead

Related

Automatically set username as "first_name-last_name" with incremental number if duplicate

I have created a registration form on wordpress using Elementor Essential Addons.
There is no "username" field in the registration form, as I would like users to login with an email address and password (they never see the actual username outside of a pre-defined url structure).
So I have set the username to automatically generate as 'first_name.'-'.last_name" in the background. This works great with the following code:
add_filter( 'pre_user_login', 'name_as_username' );
function name_as_username( $user_login ) {
if(isset($_POST['first_name'])) $first_name = $_POST['first_name'];
if(isset($_POST['last_name'])) $last_name = $_POST['last_name'];
{
$user_login = $_POST['first_name'].'-'.$_POST['last_name'];
return $user_login;
}
}
What I am struggling with is adding an incremental number at the end of the username if it already exists in my Wordpress database.
In other words, if "John-Doe" already exists, then automatically set the username to "John-Doe1". If "John-Doe1" already exists then automatically set the username to "John-Doe2" and so forth.
I have had a look at multiple other threads, but I can't seem to get any of the solutions to work:
How do I put extra number at the end of username if duplicate
Adding a number to MySQL Value If Found in DB
Below is the last full code snippet I have tried to get to work. Any help would be greatly appreciated!
add_filter( 'pre_user_login', 'name_as_username' );
function name_as_username( $user_login ) {
if(isset($_POST['first_name'])) $first_name = $_POST['first_name'];
if(isset($_POST['last_name'])) $last_name = $_POST['last_name'];
{
$user_login = $_POST['first_name'].'-'.$_POST['last_name'];
return $user_login;
$i = 0;
do {
//Check in the database here
$exists = exists_in_database($user_login);
if($exists) {
$i++;
$user_login = $user_login . $i;
}
}
while($exists);
//save $username
}
}
You're very close. You need to use the WordPress function get_user_by() to look up the login you want to check. It returns false if it doesn't find the user.
Code like this will do it.
...
$original_login = $user_login;
do {
//Check in the database here
$exists = get_user_by( 'login', $user_login ) !== false;
if($exists) {
$i++;
$user_login = $original_login . $i;
}
} while($exists);
It's certainly possible to add your own tables to WordPress, but you need to do so in a plugin or theme; they have activation and deactivation hooks allowing you to create and drop the tables. For the purpose in your question, it's not the slightest bit necessary nor helpful.

Adding Address Fields to the Registeration form in Prestashop

When a customer or user registers, I want to capture the address details in one click and save that in ps_address table , ie when he clicks on the register button his address details must be also saved to the ps_address table , how to do this?
I have managed to customize the registration form and able to plug the address details form to my registration form as shown in the attached image :
Now what I am stuck with is : when am clicking on the Register button ,the address field details are not saved in the database and I am getting server error
What I tried to do is ,I created a new function called processPostAddress and I am calling processPostAddress from processSubmitAccount() in controller/front/Authcontroller.php page before the redirection to the account page.
$this->processPostAddress(); //// custom function call
Tools::redirect('index.php?controller='.(($this->authRedirection !== false) ? urlencode($this->authRedirection) : 'my-account'));
Below is the custom function which i created in controller/front/Authcontroller.php page
public function processPostAddress()
{
if($this->context->customer->id_customer!=''){
$address = new Address();
$address->id_customer = 40;
$address->firstname = trim(Tools::getValue('firstname'));
$address->lastname = trim(Tools::getValue('lastname'));
$address->address1 = trim(Tools::getValue('address1'));
$address->address2 = trim(Tools::getValue('address2'));
$address->postcode = trim(Tools::getValue('postcode'));
$address->city = trim(Tools::getValue('city'));
$address->country = trim(Tools::getValue('country'));
$address->state = trim(Tools::getValue('state'));
$address->phone = trim(Tools::getValue('phone'));
$address->phone_mobile = trim(Tools::getValue('phone_mobile'));
$address->add(); // This should add the address to the addresss table }
}
Please help me or tell me if I am doing anything wrong or how to achieve this
I solved it by adding $address->alias, since alias was required and was validated .
Also in order to save in the database I modified $address->add(); to $address->save();
public function processPostAddress()
{
///Address::postProcess(); // Try this for posting address and check if its working
// Preparing Address
$address = new Address();
$this->errors = $address->validateController();
$address->id_customer = (int)$this->context->customer->id;
$address->firstname = trim(Tools::getValue('firstname'));
$address->lastname = trim(Tools::getValue('lastname'));
$address->address1 = trim(Tools::getValue('address1'));
$address->address2 = trim(Tools::getValue('address2'));
$address->postcode = trim(Tools::getValue('postcode'));
$address->city = (int)trim(Tools::getValue('city'));
$address->country = (int)trim(Tools::getValue('country'));
$address->state = (int)trim(Tools::getValue('state'));
$address->phone = trim(Tools::getValue('phone'));
$address->alias = "My Default Address";
// Check the requires fields which are settings in the BO
$this->errors = array_merge($this->errors, $address->validateFieldsRequiredDatabase());
// Don't continue this process if we have errors !
if (!$this->errors && !$this->ajax) {
return;
}else{
// Save address
$address->save();
}
}

Create new thread via script vbulletin

I have a script to create new thread with via scritp in vbulletin
// Create a new datamanager for posting
$threaddm =& datamanager_init('Thread_FirstPost', $vbulletin, ERRTYPE_ARRAY, 'threadpost');
// Set some variable and information
$forumid = 87; // The id of the forum we are posting to
$userid = 2;
$_POST["title"] = $vinanghinguyen_title;
$_POST["content"] = $final_content; // The user id of the person posting
$title = $_POST["title"]; // The title of the thread
$pagetext = $_POST["content"]; // The content of the thread
$allowsmilie = '1'; // Are we allowing smilies in our post
$visible = '1'; // If the post visible (ie, moderated or not)
// Parse, retrieve and process the information we need to post
$foruminfo = fetch_foruminfo($forumid);
$threadinfo = array();
$user = htmlspecialchars_uni( fetch_userinfo($userid) );
$threaddm->set_info('forum', $foruminfo);
$threaddm->set_info('thread', $threadinfo);
$threaddm->setr('forumid', $forumid);
$threaddm->setr('userid', $userid);
$threaddm->setr('pagetext', $pagetext);
$threaddm->setr('title', $title);
$threaddm->set('allowsmilie', $allowsmilie);
$threaddm->set('visible', $visible);
// Lets see what happens if we save the page
$threaddm->pre_save();
if(count($threaddm->errors) < 1) {
// Basically if the page will save without errors then let do it for real this time
$threadid = $threaddm->save();
unset($threaddm);
} else {
// There was errors in the practice run, so lets display them
var_dump ($threaddm->errors);
}
/*======================================================================*\
It can create new thread with title, forumid, userid.....but it not insert tag. I want insert with this script. thank for help

wordpress php post new blog, how to get response?

I am creating a new wp blog post via a php post. How can I get a response with the blog post id?
One way I can think of is to get the most recent blog post id, but I would like a more foolproof way of doing it.
<?php
require_once("IXR_Library.php.inc");
$client->debug = true; //Set it to false in Production Environment
$title="Blog Title"; // $title variable will insert your blog title
$body="Blog Content"; // $body will insert your blog content (article content)
$category="category1, category2"; // Comma seperated pre existing categories. Ensure that these categories exists in your blog.
$keywords="keyword1, keyword2, keyword3";
$customfields=array('key'=>'Author-bio', 'value'=>'Autor Bio Here'); // Insert your custom values like this in Key, Value format
$title = htmlentities($title,ENT_NOQUOTES,$encoding);
$keywords = htmlentities($keywords,ENT_NOQUOTES,$encoding);
$content = array(
'title'=>$title,
'description'=>$body,
'mt_allow_comments'=>0, // 1 to allow comments
'mt_allow_pings'=>0, // 1 to allow trackbacks
'post_type'=>'post',
'mt_keywords'=>$keywords,
'categories'=>array($category),
'custom_fields' => array($customfields)
);
// Create the client object
$client = new IXR_Client('Your Blog Path/xmlrpc.php');
$username = "USERNAME";
$password = "PASSWORD";
$params = array(0,$username,$password,$content,true); // Last parameter is 'true' which means post immideately, to save as draft set it as 'false'
// Run a query for PHP
if (!$client->query('metaWeblog.newPost', $params)) {
die('Something went wrong - '.$client->getErrorCode().' : '.$client->getErrorMessage());
}
else
echo "Article Posted Successfully";
?>
instead of ending with
else
echo "Article Posted Successfully";
Use:
$ID = $client->getResponse();
if ($ID)
echo 'Article Posted Successfully. ID = '.$ID;

How do I add customer billing info to a MailChimp Group when they make a purchase using WooCommerce

I have looked high and low to resolve this, but with no luck. I think I am missing something quite basic as the fix sounds pretty straight forward.
I am trying to add customer billing details to a MailChimp Group.
It is for a site that sells online courses.
What I would like to happen is:
User makes purchase on site and is automatically signed up for an appropriate MailChimp Group based on their purchase (i.e. User purchases Monthly Video Course, gets added to 'Monthly Video Course' MailChimp Group.)
I already have some code written, but it is not working (I'm getting an 'undefined variable' error). I am not sure if the variables/syntax is correct. I am by no means a coder.
Might someone be able to help me?
Here is the code I have (which I put in functions.php):
function pass_wp_to_mc() {
require_once 'inc/MCAPI.class.php';
require_once 'inc/config.inc.php'; //contains apikey
require_once 'wp-content/plugins/woocommerce/classes/class-wc-checkout.php';
$api = new MCAPI($apikey);
// Grabs the WooCommerce Product IDs and associates them with the Mailchimp Group IDs - users are put into Groups based on product purchase.
if ($product_id == 42) {
$mailchimpGroupingId = 1;
$mailchimpGroup = 'Monthly';
} elseif ($product_id == 142) {
$mailchimpGroupingId = 1;
$mailchimpGroup = 'Weekly';
} else ($product_id == 144);
$mailchimpGroupingId = 1;
$mailchimpGroup = 'Audio';
}
$merge_vars = array(
'FNAME' => $billing_first_name,
'LNAME'=> $billing_last_name,
'EMAIL'=> $billing_email,
'GROUPINGS'=>array(
array('id'=>$mailchimpGroupingId, 'groups'=>$mailchimpGroup),
)
);
$listId = 33833; //List ID found inside MailChimp on the page for your List
$my_email = '$email';
$double_optin = false; // People are automatically added in to List
$update_existing = true; // Will update users if they are already on the list
$retval = $api->listSubscribe( $listId, $my_email, $merge_vars, $double_optin, $update_existing);
if ($api->errorCode){
echo "Unable to load listSubscribe()!\n";
echo "\tCode=".$api->errorCode."\n";
echo "\tMsg=".$api->errorMessage."\n";
} else {
echo "Subscribed - look for the confirmation email!\n";
}
My questions are:
Is this code correct?
If so, is functions.php the place to put it?
If so, how do I 'call' it and where will I put the call in - WordPress file? WooCommerce? thankyou.php? checkout.php? cart.php?
Any help is greatly appreciated - I've been trying to fix this for weeks!
UPDATE: I figured it out! firstly, the code was incorrect. Here is what worked:
require_once dirname(__FILE__).'/inc/MCAPI.class.php';
require_once dirname(__FILE__).'/inc/config.inc.php';
add_action('woocommerce_checkout_order_processed', 'get_info');
function get_info($order_id) {
global $woocommerce;
$order = new WC_Order( $order_id );
$firstname = $order->billing_first_name;
$lastname = $order->billing_last_name;
$email = $order->billing_email;
$product_id=unserialize($order->order_custom_fields["_order_items"][0]);
$product_id=$product_id[0]['id'];
global $apikey;
$api = new MCAPI($apikey);
if ($product_id == *GET THIS ID AT THE EDITING SCREEN OF YOUR PARTICULAR WOOCOMMERCE PRODUCT*) {
$mailchimpGroup = '*ENTER THE NAME OF YOUR MAILCHIMP GROUP (NOT THE TITLE)*';
} elseif ($product_id == *GET THIS ID AT THE EDITING SCREEN OF YOUR PARTICULAR WOOCOMMERCE PRODUCT*) {
$mailchimpGroup = '*ENTER THE NAME OF YOUR MAILCHIMP GROUP (NOT THE TITLE)*';
} else ($product_id == *GET THIS ID AT THE EDITING SCREEN OF YOUR PARTICULAR WOOCOMMERCE PRODUCT*);
$mailchimpGroup = '*ENTER THE *NAME* OF YOUR MAILCHIMP GROUP (NOT THE TITLE)*';
$merge_vars = array(
'FNAME' => $firstname,
'LNAME'=> $lastname,
//'EMAIL'=> $email,
'GROUPINGS'=>array(
array('name'=>'*ENTER THE TITLE OF YOUR MAICHIMP GROUP (NOT THE NAME)', 'groups'=>$mailchimpGroup),
)
);
$listId = 'YOUR LIST ID HERE'; //List ID found inside MailChimp on the page for your List
$my_email = $email;
$double_optin = false; // People are automatically added in to List
$update_existing = true; // Will update users if they are already on the list
$retval = $api->listSubscribe( $listId, $my_email, $merge_vars, $double_optin, $update_existing);
There's a plugin for this now - take a look at WooChimp - MailChimp WooCommerce Integration. There are people here who do not know PHP that well so I thought this could be helpful.
Full disclosure: I'm the author of the plugin.

Categories