Skip Navigation

[Resolved] Send emails to several recipients set in several related posts to the currently edited one

This thread is resolved. Here is a description of the problem and solution.

Problem:
I have a Post Relationship and when editing or creating a Child Post I'd like to send a notification with Forms to several recipients as set in several related posts.

Solution:
That's not possible without custom code, but given there are already 2 very complete examples here in the forum you should be able to achieve any similar goal using them as reference:
https://toolset.com/forums/topic/sending-inquiry-to-multiple-emails-with-one-form-not-registered-user/#post-1370527
https://toolset.com/forums/topic/method-for-user-to-choose-post-as-favorite/#post-893150

This support ticket is created 5 years ago. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Our next available supporter will start replying to tickets in about 0.50 hours from now. Thank you for your understanding.

Sun Mon Tue Wed Thu Fri Sat
- - 14:00 – 20:00 14:00 – 20:00 14:00 – 20:00 14:00 – 20:00 14:00 – 20:00
- - - - - - -

Supporter timezone: Asia/Ho_Chi_Minh (GMT+07:00)

This topic contains 4 replies, has 2 voices.

Last updated by koheiY 5 years ago.

Assisted by: Beda.

Author
Posts
#1369917

I read this thread and I want to do almost same thing.
https://toolset.com/forums/topic/sending-inquiry-to-multiple-emails-with-one-form/

///////////////////////// My Situation /////////////////////////

I create a Travel Agency Comparison site.
I created 2 custom post type; Agencies and Messages.
Agencies and Messages are many to many relationship.

Agencies have a post custom field named "Agency Email".
In this field, a agency has their email respectively.

Messages have post custom fields named "Customer Name","Customer Email" and "Customer Telephone".
Customers input their information through Toolset Post Forms.

Agency and Customer don't have to register in my site.
They don't have wordpress user account.

///////////////////////// Work Flow /////////////////////////

A Customer accesses this page, and find his favorite agency.
hidden link

He checks some boxes, and hits the "Inquiry" button.

For example, he checks Agency01 02 04 and hits the button, he was redirected this URL.
hidden link

(I created this system by following this instruction.
https://toolset.com/learn/create-an-ecommerce-wordpress-site/product-comparison/
)

In this page ( hidden link ),
the customer inputs all form fields , and hit the submit button.

After submitting, Agency01,02,04 receive this inquiery in their mailbox.

///////////////////////// My Question /////////////////////////

1. How can I send emails to Agency01,02,04 ?
2. How can I connect a new message to selected agencies through this Toolset Form?

#1370527

I think the very simplest here is to use Custom Code.

Note, Many To Many Relationships can only be set with Relationship Forms in the front end but those cannot have Notifications or API calls, so you can NOT assign your messages with a Toolset Form to the right Agency without custom code, since you will have to use a Post Form (given you want a notification)
The Relationships can be set with the Toolset Relationships API explained here:
https://toolset.com/documentation/customizing-sites-using-php/post-relationships-api/

The emails instead will be sent with https://toolset.com/documentation/programmer-reference/cred-api/#cred_notification_recipients

Now, to proceed:
1. Create your relationship and agencies, and a email field at least for Agencies
2. List them as you do in your View passing the Post ID in the URL (?post_ids[]=7&post_ids[]=8&post_ids[]=10, etc)
3. Create a POST Form that creates new Messages
4. Attach one notification to that form, that sends an email to whatever recipient you want with the content you want (for example, you could sent it to your self, or just any dummy email you chose)
5. Insert this Form on the View (but outside the loop) where you display the agencies compared.
6. When the User now will submit this form with all details, it will send to the dummy email, but we are going to hook a custom code that will make sure it also sends it to the emails of the agencies listed in that View

This code is complex and requires custom coding, but I can make a full example here.

You will need to get the URL parameters so to get the IDs of the agencies you want to send the email to.
That's done with

$url_params = $_SERVER['QUERY_STRING'];
parse_str($url_params, $get_array);//this gives us all the URL parameters in $get_array

This gives us an array of IDs from the post_ids URL parameter (the IDs of the agencies)
From there you will need to get the Emails of those agencies, and that can be done with get_post_meta, since you have the email in a custom field.

You will want to do that foreach of the posts.

foreach ($get_array['post_ids'] as $key => $value) {
  $email_of_agency = get_post_meta($value, 'wpcf-email', true);//Change the Email Field slug as adequate
}

Now we have all the emails that we should address.
All we need to do now is use the Forms API to update the "To" of the notification, as seen here https://toolset.com/documentation/programmer-reference/cred-api/#cred_notification_recipients
We still do that within our foreach, so it's done for each of the emails:

foreach ($get_array['post_ids'] as $key => $value) {
    		$email_of_agency = get_post_meta($value, 'wpcf-email', true);
    		$recipients[] = array(
            'to'        =>  'bcc',
            'address'   => $email_of_agency,
            'name'      =>  '',
            'lastname'  =>  ''
            );
    	}

All put together into a Toolset Forms API code, that will be put in your theme's Functions File, looks like this:

add_filter('cred_notification_recipients', 'modify_recipients', 10, 4);
function modify_recipients($recipients, $notification, $form_id, $post_id) {
 
    // Check notification name matches target notification
   
 
    	$url_params = $_SERVER['QUERY_STRING'];
    	parse_str($url_params, $get_array);
    	foreach ($get_array['post_ids'] as $key => $value) {
    		$email_of_agency = get_post_meta($value, 'wpcf-email', true);
    		$recipients[] = array(
            'to'        =>  'bcc',
            'address'   => $email_of_agency,
            'name'      =>  '',
            'lastname'  =>  ''
            );
    	}
    
    error_log(print_r($recipients, true));   
    return $recipients;
}

This code is tested locally and does send the email to:
- our dummy email we set in the Notification of the Form itself
- and bcc's each of the new emails passed in the above code

Of course you will need to adapt that code to your site, and eventually you will want to use a to, instead of bcc, which is possible by altering the adequate aspects of the code as our DOC explains.
If you require help with further customization of the code, our Contractors would be the right place to ask:
https://toolset.com/contractors/

Related to connecting the message to the Post (agency) it belongs to, you can use a similar approach, but this time you'll use the Toolset Relationship API
https://toolset.com/documentation/customizing-sites-using-php/post-relationships-api/#toolset_connect_posts

Similarly you will get the ID's of the Agencies as I show above in a cred_save_data() hook https://toolset.com/documentation/programmer-reference/cred-api/#cred_save_data
In that hook you will get the IDs of the Agencies the same way as I did in the example above.
Then, you will fire toolset_connect_posts() within that hook, to connect the new message to the parent Agencies.
You can do that as well with a foreach, that for each of the Agency ID's will fire something like:

toolset_connect_posts( 'book-author', $post_id, $your_url_param_id );

Please let me know if you need more help with this, I can however help only limitedly with custom code, as explained here https://toolset.com/toolset-support-policy/

Thank you!

#1370899
m2m.JPG

Hi Beda,

Thank you! This code works fine.

I have a question.

In order to connect the message to the Post (agency), I add the code below.
Post relationship slug is "agency-message".

add_action('cred_save_data', 'connect_message_to_agency',10,2);
function connect_message_to_agency($post_id, $form_data)
{
    // if a specific form
    if ($form_data['id']==37)
    {
        $url_params = $_SERVER['QUERY_STRING'];
        parse_str($url_params, $get_array);
        foreach ($get_array['post_ids'] as $key => $value) {
		
		// connect the message to agencies
		$my_url_param_id = $value;
		toolset_connect_posts( 'agency-message',$post_id , $my_url_param_id );
	}
    }
}

The above code is not working.

I changed the line.

Before

toolset_connect_posts( 'agency-message',$post_id , $my_url_param_id );

After

toolset_connect_posts( 'agency-message',$my_url_param_id , $post_id );

After changing, it works fine.

I found my post relationship setting as attached.

Is this setting properly?
Should I chenge Agencies as Child and Messages as Parent,
and use

toolset_connect_posts( 'agency-message',$post_id , $my_url_param_id );

?

And if you have some advice about my coding, please let me know.

#1372105

According your settings, $parent would be Agencies, while $child the Message.
The Doc first lists the $parent, then $child, and the code must be:

toolset_connect_posts( 'slug', $parent, $child );

This does not correspond to your case:

toolset_connect_posts( 'agency-message',$post_id , $my_url_param_id );

It's not possible that this code works, because it should throw an error.
This, unless you have altered the aliases of the relationship.

For the code debugging I suggest:

1. Activate WP Debug and Debug log in wp-config.php like so - see https://codex.wordpress.org/Debugging_in_WordPress:

define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );

2. Then debug your code with this:

error_log(print_r($whatever_variable_you_want_to_debug, true));

The only thing you will modify is $whatever_variable_you_want_to_debug.
For example in your code that can be $post_id to be sure you have the right Post, or else.

Note, maybe you also try a hook later than cred_save_data.
Try cred_submit_complete:
https://toolset.com/documentation/programmer-reference/cred-api/#cred_submit_complete

It works the exact same as cred_save_data but later.
Toolset relationships need to be hooked later also in save_post() (which is the native WordPress hook) at priority 30, so that may be the reason it't not working in your cred_save_data as it is too early.

#1374151

My issue is resolved now. Thank you!