Send an Email to new users added to an ACF User Field - php

I am trying to have an email send when a user is added to an ACF user field, I don't want existing users that are in the field already to be notified. Below are a few options I have tried, but am not having luck with. Any assistance would be greatly appreciated.
Option 1:
add_action( 'acf/save_post', 'my_acf_save_hook_email'); function my_acf_save_hook_email( $post_id ) {
// // Get the list of user ids that are currently in the ACF field
$current_pds_project_managers = get_field('pds_project_manager');
// Get the list of user ids that were just added to the ACF field
$added_pds_project_managers = $_POST['pds_project_manager'];
// Get the list of user ids that are newly added, and not already in the ACF field
$newly_added_pds_project_managers = array_diff($added_pds_project_managers, $current_pds_project_managers);
// Send an email to each newly added user
foreach ($newly_added_pds_project_managers as $user) {
$user_email = $user['user_email'];
wp_mail( $user_email, 'You have been added to a project', 'You can now access the project from your dashboard.' );
}
}
Option 2: (this ends up sending 2 emails to the existing users in the field and one email to the new user, I then started with option one to see if I could only get the new users to no avail)
add_action( 'acf/save_post', 'my_acf_save_hook_email', 5); function my_acf_save_hook_email( $post_id ) {
// bail early if no pds_project_manager
if( empty('pds_project_manager') ) {
return; }
// Get the value of the ACF field
$project_managers = get_field('pds_project_manager', '');
// Create an empty array to store the emails
$emails_to_send = array();
// Loop through the project managers
foreach ($project_managers as $project_manager) {
// Get the user data
$user_email = $project_manager['user_email'];
$user_id = $project_manager['ID'];
// Check if the user already exists in the array
if (!in_array($user_id, $project_managers)) {
// Add the user to the emails to send
$emails_to_send[] = $user_email; } }
// Send emails to the users
foreach ($emails_to_send as $email_to_send) {
// Send the email
wp_mail($email_to_send, 'You Have Been Added To A Project', 'You have been added to a project. Please check the project page for more information.'); } }

Related

Get user mail based on username on profile page

I want to put contact form to user profile page via Contact Form 7 and Contact Form 7 Dynamic Text Extension .Form on profile page will send messages directly to user on profile page. I need to put user email to CF7 hidden field. This is only detail. Only code is important.I found a code but it's not working.
Profile Url : domain.com/member/username
I need shortcode which get user email according to username on url.
function func_print_user_email($user_email) {
global $query_string;
if($query_string != 'pagename=profile') {
$patterns = '/(\w+)=(\w+)&(\w+)=/i';
$username = preg_replace($patterns, '', $query_string);
} else {
global $current_user;
$current_user = wp_get_current_user();
$username = $current_user->user_login;
}
return trim($user_email);
return "testshortcode= { trim$user_email[testshortcode] }";
}
add_shortcode('testshortcode', 'func_print_user_email');
THANKS FOR SUPPORT

Implementing Payment Gataway in Laravel based shop

I need a little help with implementing payment getaway in Laravel shop.
Payment I use is https://gourl.io/ and I can't understand how to take needed information. So I have set the files database table, database connection and all.. Now I'm trying to redirect user to payment.php page after order form is submitted. This is my CartController.php orderSubmit function
public function orderSubmit() {
$cart = Session::get(self::CART_SESSION_KEY, array());
if (count($cart) < 1) {
return Redirect::to('/');
}
$validatorRules = array(
'captcha' => 'required|captcha',
'shipping_address' => 'required|min:10',
'shipping_method' => 'required|in:' . implode(',', [Settings::SETTINGS_SHIPPING_NORMAL, Settings::SETTINGS_SHIPPING_EXPRESS])
);
Input::merge(array_map('trim', Input::all()));
$validator = Validator::make(Input::all(), $validatorRules);
if ($validator->fails()) {
return Redirect::to('/cart/order?_token=' . csrf_token())->withErrors($validator->errors())->withInput(Input::except(['captcha']));
}
$shipping = array(
'quantity' => 1,
'image' => '/img/noimage.png',
'description' => '',
'title' => 'FIX ME', // this should never occur,
'price' => 100000 // this should never occur
);
switch (Input::get('shipping_method')) {
case Settings::SETTINGS_SHIPPING_NORMAL:
$shipping['title'] = 'Normal Delivery';
$shipping['price'] = 0;
break;
case Settings::SETTINGS_SHIPPING_EXPRESS:
$shipping['title'] = sprintf('Express Delivery - $%.2f', Settings::getOption('express_shipping_cost'));
$shipping['price'] = doubleval(Settings::getOption('express_shipping_cost'));
break;
}
$cart['shipping'] = $shipping;
$order = new Order();
$order->user_id = self::$user->user_id;
$order->data = json_encode($cart);
$order->address = Input::get('shipping_address');
$order->pgp_key = Input::get('gpgkey');
$order->info = Input::get('additional_info');
$order->save();
Session::put(self::CART_SESSION_KEY, array());
return Redirect::to('payment.php')->with('message_success', 'Order created! We will contact you shortly to confirm your order and payment details.');
}
and this is payment.php
require_once( "../cryptobox.class.php" );
/**** CONFIGURATION VARIABLES ****/
$userID = ""; // place your registered userID or md5(userID) here (user1, user7, uo43DC, etc).
// you don't need to use userID for unregistered website visitors
// if userID is empty, system will autogenerate userID and save in cookies
$userFormat = ""; // save userID in cookies (or you can use IPADDRESS, SESSION)
$orderID = "";
$amountUSD = 20;
$period = "NOEXPIRY";
$def_language = "en";
$public_key = "mypublickey";
$private_key = "myprivatekey";
/** PAYMENT BOX **/
$options = array(
"public_key" => $public_key, // your public key from gourl.io
"private_key" => $private_key, // your private key from gourl.io
"webdev_key" => "", // optional, gourl affiliate key
"orderID" => $orderID, // order id or product name
"userID" => $userID, // unique identifier for every user
"userFormat" => $userFormat, // save userID in COOKIE, IPADDRESS or SESSION
"amount" => 0, // product price in coins OR in USD below
"amountUSD" => $amountUSD, // we use product price in USD
"period" => $period, // payment valid period
"language" => $def_language // text on EN - english, FR - french, etc
);
// Initialise Payment Class
$box = new Cryptobox ($options);
// coin name
$coinName = $box->coin_name();
// Successful Cryptocoin Payment received
if ($box->is_paid())
{
if (!$box->is_confirmed()) {
$message = "Thank you for payment (payment #".$box->payment_id()."). Awaiting transaction/payment confirmation";
}
else
{ // payment confirmed (6+ confirmations)
// one time action
if (!$box->is_processed())
{
// One time action after payment has been made/confirmed
$message = "Thank you for order (order #".$orderID.", payment #".$box->payment_id()."). We will send soon";
// Set Payment Status to Processed
$box->set_status_processed();
}
else $message = "Thank you. Your order is in process"; // General message
}
}
else $message = "This invoice has not been paid yet";
$languages_list = display_language_box($def_language);
My question is how to take the correct info in the payment.php? How to take userID, userFormat, orderID and so on?
First of all, I would suggest you use Laravel as the framework it is intended for. In Laravel you define controllers to handle your http-requests. Make a new PaymentController and put the code from payment.php into this controller. Then make a route to that controller-method.
Also put your configuration settings in Laravels config-folder.
And the require_once( "../cryptobox.class.php" ); can be replaced by a dependency injection in your controllers constructor.
Now back to your question.
$userID is where you put your registered Laravel user ID. (If you dont have any registered users, leave it blank). Why you should put your user's id in this variable? -It helps to keep track of which users have done which payments. You can later save this information in your database if you want to keep track of payment history.
$orderID This is where you put your internal order id. Why should you use an internal order id? -Again its to keep track of which purchases of which products have been done by which users. You can store your order-id in your database together with user-id and product-id to get a purchase history log.
$userFormat This is how you wish to store your user information, session, cookie, etc. Because when the purchase is executed, the payment gateway needs a way to access this information, and therefor it must be stored in the session or in a cookie.
I would use $_SESSION['$value'] if you use session for your users!

Laravel saving post variable when there is validation error?

I am using laravel 4 , and I have a form with checkboxes and on sumbitting the form , it goes through the validation error process, if there is error how do I make it save the post values of these check boxes?
AdminRolesController:
public function postActions($action = NULL) {
// Allowed post actions..
$allowed = array('add', 'edit');
$action = in_array($action, $allowed) ? $action : NULL;
// check if action is not null
if(is_null($action))
return Redirect::to('admin/roles');
else
{
// POST ACTION
if($action == "add")
{
// put all your rules.
$rules = array(
'name'=>'required|regex:/^[a-zA-Z ]*$/|min:2',
'permission_ids' =>'required'
);
// run the validation rules on the inputs from the form
$validator = Validator::make(Input::all(), $rules);
// get all permissions or groups available
$perms = Permissions::all();
// share it to the view
// we have two parts of permissions ( 0 , 1)
// 0 : Admin Group Pages , 1: Front End Pages
View::share('perms', $perms);
if ($validator->passes())
{
// validation has passed, save user in DB
// create instance of our model..
// create a new role
$role = new Role;
$role->name = Input::get('name');
$permission_ids = Input::get('permission_ids');
// save info to db.
$role->save();
$msg = 'Role '.$role->name.' has been added';
}// end validation if
else
{
// validation has failed, display error messages
return Redirect::back()->with('message', 'The following errors occurred:')->withErrors($validator)->withInput();
}
}// end if add
}
}
I think part of the problem me redirecting with error messages , all the post values is lost , how could I still keep them?
Thanks
Your controller looks fine - all that's required to do to pass input back to the view is chaining ->withInput()
However, in your views, ensure you're populating the form using the old input values. You can do so, using Blade, by doing something like:
{{ Form::checkbox('permission_id', 'value', Input::old('permission_id)) }}

Codeigniter form post and validation

I'm not a pro, but know my way around PHP, I'm new to Codeigniter.
Been going through these tutorials: http://net.tutsplus.com/articles/news/codeigniter-from-scratch-day-5-crud/
OK, so I have a page that lists users, clicking on users name will go to an edit page, the url of that page being: index.php/users/edit/1 (where 1 is the users id)
On edit page is a form, this form contains a few parts, each part is populated from different tables in the DB. So my Controller for edit is as follows:
function edit() {
//load model
$this->load->model('users_model');
//assign user data from DB
$data['data_user'] = $this->users_model->getUser($this->uri->segment(3));
//get users Password, using username from above
$data['data_user_password']= $this->users_model->getUserPassword($data['data_user'][0]->UserName);
$data['page_content'] = 'pages/users_edit';
$this->load->view('template/template', $data);
}
Notice:
$data['data_user'] contains users data like name, username, email
$data['data_user_password'] contains users password from a different table
I can then populate the form, on users_edit.php, this all works fine.
I'm accessing this data by doing the following:
if (is_array($data_user)) {
foreach($data_user as $user)
{
$userID = $user->id;
$userName = $user->Name;
$userUserName = $user->UserName;
$userMail = $user->Mail;
$userDepartment = $user->Department;
$userWorkPhone = $user->WorkPhone;
$userHomePhone = $user->HomePhone;
$userMobile = $user->Mobile;
}
}
//user password
if (is_array($data_user_password)) {
foreach($data_user_password as $user)
{
$userPassword = $user->value;
}
}
Name:
<?php echo form_input('name', set_value('name', $userName), 'id="name" class="inputLong"'); ?>
When I post, I'm sending data to: index.php/users/update
My controller for this page so far is:
function update() {
echo '<pre>';
print_r($_POST);
echo '</pre>';
//exit();
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'Name', 'trim|required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('pages/users_edit');
}
else
{
$this->index();
}
}
For now, I'm just testing validation on users "name" where form input=name id=name
I think I'm not handling the if ($this->form_validation->run() == FALSE) part of it correctly, if the form contains data, it passes and redirects to index, if I leave name blank it either not handling the edit page correctly, or I dont know, something isnt right.. I think its because the page is being reloaded using the post array, and not passing the $data like I did in function edit().
Back to the form page, where it should be showing the validation_errors, its showing:
The Name field is required.
This is correct, however, for the rest of the fields that should be pre-populated, its showing PHP error:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: userUserName
Filename: pages/users_edit.php
Line Number: 50
You could do your validation inside your edit function instead of having an update function, that way, your data is still available for your view and if the validation has errors, codeigniter will take in charge to repopulate your fields. If the validation is ok, you do your next step
function edit() {
//load model
$this->load->model('users_model');
//assign user data from DB
$data['data_user'] = $this->users_model->getUser($this->uri->segment(3));
//get users Password, using username from above
$data['data_user_password']= $this->users_model->getUserPassword($data['data_user'][0]->UserName);
$data['page_content'] = 'pages/users_edit';
$this->load->view('template/template', $data);
//is the form submitted
if(form submit){
if ($this->form_validation->run() == TRUE)
{
$this->index();
}
else
{
$this->load->view('pages/users_edit', $data);
}
}
}
$this->load->view('pages/users_edit');
Inside your function update(), after your validation you load view but you don't PASS any data variables to it. So you don't have any variables which you can access at your view file..
You have to set your variables the same way as in your function edit():
$this->load->view('template/template', $data);
Currently there is not set variable $data_user so you can't loop it and use it..

How to get the currently logged in user's role in wordpress?

How to get the currently logged in user's role in wordpress?
Assuming you have the user id ($user_id) something like this should work:
$user = new WP_User( $user_id );
if ( !empty( $user->roles ) && is_array( $user->roles ) ) {
foreach ( $user->roles as $role )
echo $role;
}
Get the user id from your session.
If you don't know the user id, this function will help you (put it in your theme functions.php file)
function get_user_role() {
global $current_user;
$user_roles = $current_user->roles;
$user_role = array_shift($user_roles);
return $user_role;
}
And then, in your template you can get user role by calling get_user_role().
Found it here.
function get_role_by_id( $id ) {
if ( !is_user_logged_in() ) { return false; }
$oUser = get_user_by( 'id', $id );
$aUser = get_object_vars( $oUser );
$sRole = $aUser['roles'][0];
return $sRole;
}
<?php global $current_user; //get the current user
echo $current_user->roles[0]); //display the current user's role
?>
This is an old question but I thought I'd add this 2023 option for getting the currently logged in user's role in WordPress. By default, WordPress users only have one role, but there are plugins and themes that can extend that feature giving users multiple roles, so I wanted to provide options for that too.
First, add this function somewhere to your website, probably at the bottom of your active theme's functions.php file.
/**
* Get Current User Roles
*
* #param bool $return_array Optional. If true, will return an array of all roles. Otherwise, will return just the first role. Default is false.
*
* #return string|array Returns the current user's role(s) based on parameters. Empty string or array if user is not logged in or has no roles.
*/
function au_get_current_user_roles($return_array = false) {
// Retrieves the current user
$current_user = wp_get_current_user();
// Checks if user is logged in and has roles
if($current_user->exists() && count($current_user->roles)) {
if($return_array) { return $current_user->roles; } // Return all roles as array
return $current_user->roles[0]; // Return just the first role as a string
}
if($return_array) { return array(); } // Return empty array
return ''; // Return empty string
}
To use the function to check if a user has a specific role (e.g. administrator) where users can only have one role, you'd use the function like this:
if('administrator' == au_get_current_user_roles()) {
// Do something for admins only
}
Now if your users can have multiple roles and you want to check if they have a specific one (e.g. administrator), you can do it like this:
if(in_array('administrator', au_get_current_user_roles(true))) {
// Do something for admins only
}
Now those examples above just checked if a user is a specific role (administrator), but what if you want to do something for users that are either an admin or an editor? Or both? You can do something like this:
$allowed_roles = array('administrator', 'editor');
if(count(array_intersect($allowed_roles, au_get_current_user_roles(true)))) {
/* Do something for users who are admins, users who
are editors, and users who are both admin and users */
}

Categories