Support

Account

Home Forums Front-end Issues Trigger Email On Front End Form Update

Solving

Trigger Email On Front End Form Update

  • Hi All,
    I’m really hoping someone can help as the below is driving me mad!!!

    I have a page that has 2 forms, depending on a condition, depends which form is displayed (works fine).

    These are the 2 forms:

    					acf_form(array(
    						'field_groups' => array(63),
    						'post_id' => 'user_'.get_current_user_id(),
    						'submit_value'	=> 'Update Premium Details',
    						'updated_message' => __("Premium Details Updated", 'acf'),
    						'html_after_fields' => '<input type="hidden" name="acf[update]" value="true"/>',
    					)); 

    AND

    					acf_form(array(
    						'field_groups' => array(183),
    						'post_id' => 'user_'.get_current_user_id(),
    						'submit_value'	=> 'Update Standard Details',
    						'updated_message' => __("Standard Details Updated", 'acf'),
    						'html_after_fields' => '<input type="hidden" name="acf[update]" value="true"/>',
    					)); 

    I then have the following in my functions file:

    add_action('acf/save_post', 'my_save_post');
    
    function my_save_post( $post_id ) {
    		
    	# add conditional to check form was triggered
    	if(($_POST['acf']['update'] == 'true')) {
    	
    	# bail early if editing in admin
    	if( is_admin() ) {		
    		return;		
    	}
    		
    	# vars
    	$post = get_post( $post_id );	
    	
    	# get custom fields (field group exists for content_form)
    	# need to extract user ID
    	$user_id = str_replace("user_", "", $post_id);	
    	
    	# get user registration details
    	$user_info = get_userdata($user_id);
    	$first_name = $user_info->first_name;
    	$last_name = $user_info->last_name;
    	$user_email = $user_info->user_email;
    	$user_login = $user_info->user_login;
    	
    	$active = get_field('display_in_directory', $post_id);
    	if ($active == true ) {
    		$status = 'Yes';
    	} else {
    		$status = 'No';	
    	}	
    	
    	# email data
    	$to = get_bloginfo('admin_email');
    	$headers = 'From: ' . $user_info->first_name. ' '.$user_info->last_name . ' <' . $user_email .'>' . "\r\n";
    	$subject = 'Profile Updated';
    	$body = $user_info->first_name. ' '.$user_info->last_name. ' has updated their profile' . "\r\n";
    	$body .= 'They are registered with a username name of ' . $user_login . "\r\n";
    	$body .= 'Active in directory? ' . $status . "\r\n";
    		
    	# send email
    	wp_mail($to, $subject, $body, $headers );
    	
    	}
    	
    }

    Now, when I update the page with the 2nd form (‘field_groups’ => array(183),) the function triggers and I get the email

    Yet when I update the page with the 1st form (‘field_groups’ => array(63),)
    the email never gets triggered

    For the life of me, I can’t see why?

    Any pointers would be very much appreciated!!!

    Thanks in advanced

  • Hi @jarvis

    Because this is related to the wp_mail() function, I think the easiest way to find the issue is to check your PHP error log. Could you please check it and see if there are any related error messages?

    Also, could you please share the JSON or XML export file of your field group so I can check your setup?

    Thanks 🙂

  • Thanks @acf-support

    I managed to work it out!

    I added:

    
    	$mailResult = false;
    	#$mailResult = wp_mail( '[email protected]', 'test if mail works', 'hurray' );
    	echo $mailResult;	
    

    I then worked out I had a typo!
    This line:
    $headers = 'From: ' . $user_info->first_name. ' '.$user_info->last_name . ' <' . $user_email .'>' . "\r\n";

    Should be:
    $headers = 'From: ' . $user_info->first_name. ' '.$user_info->last_name . ' <' . $user_info->user_email .'>' . "\r\n";

    Basically, the email didn’t have $user_info-> in front of it!

    Now working

    Cheers

  • Apologies, I missed this part:
    $headers = array('From: ' . $user_info->first_name. ' '.$user_info->last_name . ' <'.$user_info->user_email.'>');
    Notice the header is an array!

  • Hey Jarvis – not sure if you’re still active here, but if you are, I’d love to pick your brain with something! I was going through your PHP and it seems to be in line with something I’m working on. I have a front end form and want emails to trigger to the USER (post author) every time a post is added or updated. But as an added headache, I also want it to be triggered on a specific date(s) and time(s) set by the user. If you (or anyone reading this) can share some wisdom, I’d appreciate that!

  • Hi @prithsr

    Ok, if I’ve understood right, here’s how I think I’d possibly approach it:

    I’d use the acf/save_post function:

    add_action('acf/save_post', 'my_acf_save_post');
    function my_acf_save_post( $post_id ) {
    
        // Get newly saved values.
        $values = get_fields( $post_id );
    
        // Get post author ID
        $author_id = get_post_field ('post_author', $post_id);
    
        // Add a custom field to the user 
        update_user_meta( $author_id, 'some_custom_field', '1' );
    
    }

    You could then query the users via a php file you run on cron:

    
    	#query our users
    	$args  = array(
    		'role__in'     	=> array('editor'),
    		'role__not_in' 	=> array('administrator'),
    		'exclude'      	=> array(1),	
            'meta_query'        => array(
    			array(
    				'key'       => 'some_custom_field',
    				'value'     => 1
    			)
            )					
    	);	
    	$user_query = new WP_User_Query( $args );
    	$user = get_userdata( $user->ID );
    

    You could wrap the whole query in a date check to compare the current date with the date set by the user

    If the date matches and the query returns a result, you can then reset the custom meta for the user/author:

        // Reset custom field to the user 
        update_user_meta( $user->ID, 'some_custom_field', '0' );

    So roughly the email function could look like:

    ###################################################
    # Send Emails When custom_post_typePublished
    ###################################################
    add_action( 'transition_post_status', 'send_email_notification', 10, 3 );
    function send_email_notification( $new_status, $old_status, $post ) {
    
    	if ( 'publish' !== $new_status or 'publish' === $old_status || 'custom_post_type' !== get_post_type( $post ) )
    	return;
    	
    	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
    	return;	
    	
    	#get the post ID, we can now use this on both publish and update functions
    	$post_id = $post->ID;	
    	
    	#add date check here
    	$todays_date = '';
    	$specific_date  = '';
    	if ($todays_date == $specific_date ) {
    
    		#query our users
    		$args  = array(
    			'role__in'     	=> array('subscriber'),
    			'role__not_in' 	=> array('administrator'),
    			'exclude'      	=> array(1),	
    			'meta_query'        => array(
    				array(
    					'key'       => 'some_custom_field', //only want to send to specific users
    					'value'     => '1'
    				)
    			)					
    		);	
    		$user_query = new WP_User_Query( $args );
    		
    		#get our email data if we have any results
    		if ( ! empty( $user_query->get_results() ) ) {
    			#create an array
    			$email_recipients = array();
    			foreach ( $user_query->get_results() as $user ) {
    				$user = get_userdata( $user->ID );
    					
    				$email_recipients[] = array(
    					'forename'	=> $user->first_name,
    					'email'		=> $user->user_email
    				);	
    				
    				update_user_meta( $user->ID, 'some_custom_field', '0' ); //reset the custom meta until front end form retriggers
    			}
    		}
    		
    		#filter duplicates (may not need this)
    		#$email_recipients = array_unique($email_recipients);	
    		
    		#proceed with the email if we have a result
    		if ($email_recipients) {
    	
    			foreach ($email_recipients as $recipients) {			
    	
    				$to			= $recipients['email'];
    				$subject	= "Email Subject Goes Here";
    				$message	= "<p>Dear {$recipients['forename']}</p>";
    	
    				#create the headers
    				$headers = array(
    					'Content-Type: text/html; charset=UTF-8',
    					#'Cc:' . '[email protected]',
    					#'Bcc:' . '[email protected]',				
    					'From: '.get_option( 'blogname' ).' <[email protected]>'
    				);	
    				#send the email
    				wp_mail ($to, $subject, $message, $headers);					
    			}
    		}	
    	
    	}
    
    }

    It may require some spit and polish but should be a rough starting point I hope!?

    Cheers

  • Hi @prithsr

    Just one other thought on this.

    You may need to move the date check conditional into the user results loop, this is because I assume the date info is set against the user, therefore, as you then get the user->ID from the user results loop, you can then access those custom fields!

    Cheers

  • @jarvis It will take some time for me to understand what’s going on here and where to implement this, but it’s more help than I could have asked for. Much appreciated!!

  • Hi @prithsr ,

    No problem. It would go in the functions file.

    I’ve tried to add notes to help but appreciate it may not make sense

    Any questions, let me know

    Cheers

Viewing 9 posts - 1 through 9 (of 9 total)

The topic ‘Trigger Email On Front End Form Update’ is closed to new replies.