• I’m currently trying to have my private training site email the admins when a page is visited by a logged in user. I have it set up so that it deposits a cookie upon the first visit and sends then email, then upon consequential visits it send a different message with the “last visit” timestamp. I want this to do nothing if it does not detect the correct page ID. This is to ensure that it only runs the function when the user is on the specific page!

    I have verified it is being placed into the functions.php file correctly, the email addresses used are correct, the post ID is correct and the message content is correct as well.

    Sometimes it does not display the $User correctly and it also starts an infinite loop of sending many emails at once!

    Any help is greatly appreciated!

    (any references to ’email-address-here’ are normal email addresses when used lived… I just changed them here to keep them private)

    function application_notification() {
    
    $visit_time = date('F j, Y g:i a');
    $postid = get_the_ID();
    
    if(!isset($_COOKIE['first_app_notification_visit_time']) && !$postid = 1388) {
    
    
    
            $last_app_page_visit = $_COOKIE['first_app_notification_visit_time'];
    
                        $user = wp_get_current_user();
                        $user_email = $user->user_email;
    
                        $to ="email-address-here";
    
                        $subject = "First App Page Viewed Again";
    
                        $msg = 'User and User, <br> <br>';
                        $msg .= "$user_email";
                        $msg .= "just opened the page to begin their first application for the again. The last time they viewed it was on <br> " ;
                        $msg .= "$last_app_page_visit";           
    
                        $headers  = 'MIME-Version: 1.0' . "\r\n";
                        $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
                        $headers .= 'From: Training Site <email-address-here>' . "\r\n";
                        $headers .= 'CC: email-address-here' . "\r\n";
    
                        wp_mail($to, $subject, $msg, $headers);
    
                        unset($_COOKIE['first_app_notification_visit_time']); 
                        setcookie('first_app_notification_visit_time',  $visit_time, time()+31556926);
            }
    
    
            else ($postid = 1388) { 
    
                        $to ="email-address-here";
    
                        $subject = "First App Page Viewed";
    
                        $msg = 'User and User, <br> <br>';
                        $msg .= "$user_email";
                        $msg .= "just opened the page on the training site to begin their first application for the first time!" ;     
    
                        $headers  = 'MIME-Version: 1.0' . "\r\n";
                        $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
                        $headers .= 'From: Training Site <email address here>' . "\r\n";
                        $headers .= 'CC: email-address-here' . "\r\n";
    
                        wp_mail($to, $subject, $msg, $headers); 
    
                        setcookie('first_app_notification_visit_time', true, time()+31556926);
            }   
    }
    }
    }
    add_action('init', 'application_notification');
Viewing 15 replies - 1 through 15 (of 27 total)
  • Moderator bcworkz

    (@bcworkz)

    A little documented fact is some action hooks can fire more than once per request. IDK if “init” is one of them, but it’s possible.

    Anyway, anytime any action or filter callback does something that would be problematic to repeat for the same request, such as sending an email or incrementing a counter, the callback should remove itself from the call stack during the first pass through so it cannot be called again until the next request happens.
    remove_action('init', 'application_notification');

    Thread Starter scottstarl

    (@scottstarl)

    Interesting! Thanks for responding. So what you’re saying is that it should look like what I typed below? Or should it just be ended once at the end since the “else” function can only be activated if the first “if” is false?

    function application_notification() {
    
    $visit_time = date('F j, Y g:i a');
    $postid = get_the_ID();
    
    if(!isset($_COOKIE['first_app_notification_visit_time']) && !$postid = 1388) {
    
    
    
            $last_app_page_visit = $_COOKIE['first_app_notification_visit_time'];
    
                        $user = wp_get_current_user();
                        $user_email = $user->user_email;
    
                        $to ="email-address-here";
    
                        $subject = "First App Page Viewed Again";
    
                        $msg = 'User and User, <br> <br>';
                        $msg .= "$user_email";
                        $msg .= "just opened the page to begin their first application for the again. The last time they viewed it was on <br> " ;
                        $msg .= "$last_app_page_visit";           
    
                        $headers  = 'MIME-Version: 1.0' . "\r\n";
                        $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
                        $headers .= 'From: Training Site <email-address-here>' . "\r\n";
                        $headers .= 'CC: email-address-here' . "\r\n";
    
                        wp_mail($to, $subject, $msg, $headers);
    
                        unset($_COOKIE['first_app_notification_visit_time']); 
                        setcookie('first_app_notification_visit_time',  $visit_time, time()+31556926);
            }
    
    
            else ($postid = 1388) { 
    
                        $to ="email-address-here";
    
                        $subject = "First App Page Viewed";
    
                        $msg = 'User and User, <br> <br>';
                        $msg .= "$user_email";
                        $msg .= "just opened the page on the training site to begin their first application for the first time!" ;     
    
                        $headers  = 'MIME-Version: 1.0' . "\r\n";
                        $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
                        $headers .= 'From: Training Site <email address here>' . "\r\n";
                        $headers .= 'CC: email-address-here' . "\r\n";
    
                        wp_mail($to, $subject, $msg, $headers); 
    
                        setcookie('first_app_notification_visit_time', true, time()+31556926);
            }   
    }
    }
    }
    add_action('init', 'application_notification');
    function application_notification() {
    
    $visit_time = date('F j, Y g:i a');
    $postid = get_the_ID();
    
    if(!isset($_COOKIE['first_app_notification_visit_time']) && !$postid = 1388) {
    
    
    
            $last_app_page_visit = $_COOKIE['first_app_notification_visit_time'];
    
                        $user = wp_get_current_user();
                        $user_email = $user->user_email;
    
                        $to ="email-address-here";
    
                        $subject = "First App Page Viewed Again";
    
                        $msg = 'User and User, <br> <br>';
                        $msg .= "$user_email";
                        $msg .= "just opened the page to begin their first application for the again. The last time they viewed it was on <br> " ;
                        $msg .= "$last_app_page_visit";           
    
                        $headers  = 'MIME-Version: 1.0' . "\r\n";
                        $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
                        $headers .= 'From: Training Site <email-address-here>' . "\r\n";
                        $headers .= 'CC: email-address-here' . "\r\n";
    
                        wp_mail($to, $subject, $msg, $headers);
    
                        unset($_COOKIE['first_app_notification_visit_time']); 
                        setcookie('first_app_notification_visit_time',  $visit_time, time()+31556926);
    remove_action('init', 'application_notification');
            }
    
    
            else ($postid = 1388) { 
    
                        $to ="email-address-here";
    
                        $subject = "First App Page Viewed";
    
                        $msg = 'User and User, <br> <br>';
                        $msg .= "$user_email";
                        $msg .= "just opened the page on the training site to begin their first application for the first time!" ;     
    
                        $headers  = 'MIME-Version: 1.0' . "\r\n";
                        $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
                        $headers .= 'From: Training Site <email address here>' . "\r\n";
                        $headers .= 'CC: email-address-here' . "\r\n";
    
                        wp_mail($to, $subject, $msg, $headers); 
    
                        setcookie('first_app_notification_visit_time', true, time()+31556926);
    remove_action('init', 'application_notification');
            }   
    }
    }
    remove_action('init', 'application_notification');
    }
    add_action('init', 'application_notification');
    Moderator bcworkz

    (@bcworkz)

    The last one alone outside of any conditionals should be adequate.

    Thread Starter scottstarl

    (@scottstarl)

    Still acting very buggy… I’ve been testing a bunch of different ways and this is where I’ve ended up. Sometimes it doesn’t grab the username at all, other times it doesn’t grab the time at all. It also still starts an infinite loop of sending emails that doesn’t stop unless I remove the snippet, everything else seems to be working normally though.

    function application_notification() {
    $visit_time = date('m/d/Y g:i a');
    $expiration_time = 365 * DAY_IN_SECONDS;
    if(is_page( 1388 )) {
    if(isset($_COOKIE['first_app_notification_visit_time'])) {
    $last_app_page_visit = $_COOKIE['first_app_notification_visit_time'];
    $user = wp_get_current_user();
    $user_email = $user->user_email;
    $to ="private-email-here";
    $subject = "First App Page Viewed Again";
    $msg = 'NAME,
    
    ';
    $msg .= "$user_email";
    $msg .= "just opened the page to begin their first application for the again. The last time they viewed it was on
    " ;
    $msg .= "$last_app_page_visit";
    $msg .= 'The time is currently: ';
    $msg .= "$visit_time";
    $headers = 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
    $headers .= 'From: Training Site <private-email-here>' . "\r\n";
    $headers .= 'CC: private-email-here' . "\r\n";
    wp_mail($to, $subject, $msg, $headers);
    unset($_COOKIE['first_app_notification_visit_time']);
    setcookie('first_app_notification_visit_time', $visit_time, time() + $expiration_time, COOKIEPATH, COOKIE_DOMAIN);
    return wp_mail;
    ) else {
    $user = wp_get_current_user();
    $user_email = $user->user_email;
    $to ="private-email-here";
    $subject = "First App Page Viewed";
    $msg = 'NAME,
    
    ';
    $msg .= "$user_email";
    $msg .= "just opened the page on the training site to begin their first application for the first time!
    
    " ;
    $msg .= 'The time is currently: ';
    $msg .= "$visit_time";
    $headers = 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
    $headers .= 'From: Training Site <private-email-here>' . "\r\n";
    $headers .= 'CC: private-email-here' . "\r\n";
    wp_mail($to, $subject, $msg, $headers);
    setcookie('first_app_notification_visit_time', $visit_time, time() + $expiration_time, COOKIEPATH, COOKIE_DOMAIN);
    return wp_mail;
    ) else {}
    remove_action('init', 'application_notification');
    }
    add_action('init', 'application_notification');
    Moderator bcworkz

    (@bcworkz)

    There are a few syntax errors, so I don’t see how this was working at all. Are you sure there’s no other versions active somewhere? For example:

    return wp_mail;
    ) else {}

    I’m not sure what wp_mail is supposed to represent here. Action hooks are not expecting a return value so you probably don’t need the return line at all. It’s OK to return anyway if it helps with readability, but wp_mail appears to be an invalid return value.

    There’s a parenthesis) instead of curly brace{ before the elses. Even with those corrections the opening and closing braces don’t match. I’m not sure where it’s missing, only that there’s a mismatch. If you were to indent code demarcated with braces it might be more apparent what’s missing where.

    Thread Starter scottstarl

    (@scottstarl)

    Sorry about that, I might seem incompetent because I had zero experience with any coding including html prior to starting my 2 websites a month ago… I retyped the code last time that I pasted it here and had some typos.

    I have had some progress in the last day, everything is working properly now, except for still receiving duplicate emails. I have put a random number generator in the subject line and observed that it is outputting different numbers each time, so the code is being repeated somehow. I have moved the remove_action command to different places in the snippet and had no luck yet. I even tried pasting it into every single bracket and it didn’t do anything. This is the latest version that is only having the final issue I mentioned. Again, any help again is appreciated!

    // Loop to start
    add_action( 'application_notification' );
    
    // Pimary function to run inside loop
    function application_notification() {
    
        // Grabs the currents pages id
        $postid = get_the_ID();
    
    
        // Check if page id is correct, then run the commands if so
        if( $postid = 1388 ) {
    
            // Check if cookie is set or otherwise if user has visited this page before, then run commands if so
            if( isset( $_COOKIE['first_app_time'] ) ) {
    
                // Email and cookie constants
                    // Headers
                    $headers = 'MIME-Version: 1.0' . "\r\n";
                    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
    
    
                    // Where the email is sent, seperated by commas
                    $to ="email, email";
    
                    // Time of visit
                    $current_date_time = current_datetime()->format('m/d/Y g:i a');
    
                    // Time of most recent visit that was stored in the cookie
                    $last_app_page_visit = $_COOKIE['first_app_time'];
    
                    // How long the cookie lasts, the number is the amount of days
                    $expiration_time = 365 * DAY_IN_SECONDS;
    
                    // Grabs the data for the user currently viewing the page
                    $user = wp_get_current_user();
    
                    // Full name of the user
                    $display_name = $user->display_name;
    
                    // Email of the user
                    $user_email = $user->user_email;
    
                // All of these are added together to create the email subject, use .$subject for subsequent lines, values need their own line
                $subject = "Application Viewed Again By: "  . rand(0,1000000);
                $subject .= "$display_name";
    
                // All of these are added together to create the email body, use .$msg for subsequent lines, values need their own line
                $msg = 'name & name,<br/><br/>';
                $msg .= "$display_name";
                $msg .= " (";
                $msg .= "$user_email";
                $msg .= ") ";
                $msg .= "just opened the page to begin their application again.<br/><br/>The last time they viewed it was on: " ;
                $msg .= "$last_app_page_visit";
                $msg .= '</br><br/>The time is currently: ';
                $msg .= "$current_date_time";
    
                // Send email
                wp_mail( $to, $subject, $msg, $headers );
    
                // Remove cookie so we can reset the timestamp
                unset( $_COOKIE['first_app_time'] );
    
                // Set the cookie with the current time
                setcookie( 'first_app_time', $current_date_time, time() + $expiration_time );
    
            // If cookie is not set or otherwise the user has not visited this page before, but the page number is correct, run these commands instead
            } else {
    
                // Email and cookie constants
                    // Headers
                    $headers = 'MIME-Version: 1.0' . "\r\n";
                    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
    
    
                    // Where the email is sent, seperated by commas
                    $to ="email, email";
    
                    // Time of visit
                    $current_date_time = current_datetime()->format('m/d/Y g:i a');
    
                    // How long the cookie lasts, the number is the amount of days
                    $expiration_time = 365 * DAY_IN_SECONDS;
    
                    // Grabs the data for the user currently viewing the page
                    $user = wp_get_current_user();
    
                    // Full name of the user
                    $display_name = $user->display_name;
    
                    // Email of the user
                    $user_email = $user->user_email;
    
                // All of these are added together to create the email subject, use .$subject for subsequent lines, values need their own line
                $subject = "name First Time View: " . rand(0,1000000);
                $subject .= "$display_name";
    
                // All of these are added together to create the email body, use .$msg for subsequent lines, values need their own line
                $msg = 'name & name,<br/><br/>';
                $msg .= "$display_name";
                $msg .= " (";
                $msg .= "$user_email";
                $msg .= ") ";
                $msg .= "just opened the page to begin their application for the first time!" ;
                $msg .= '</br><br/>The time is currently: ';
                $msg .= "$current_date_time";
    
                // Send email
                wp_mail( $to, $subject, $msg, $headers );
    
                // Set the cookie with the current time
                setcookie( 'first_app_time', $current_date_time, time() + $expiration_time ); 
    
    
            }       
    
    }
    // Stops action only if it has run, this prevents looping and will only allow it to run again when the page is loaded again
    remove_action( 'application_notification' );
    }

    and here’s the condensed snippet without my notes, the paragraph blocks here don’t save the indention of the lines so it’s less organized:

    add_action( 'application_notification' );
    function application_notification() {
    $postid = get_the_ID();
    if( $postid = 1388 ) {
    if( isset( $_COOKIE['first_app_time'] ) ) {
    $headers = 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
    $to ="email, email";
    $current_date_time = current_datetime()->format('m/d/Y g:i a');
    $last_app_page_visit = $_COOKIE['first_app_time'];
    $expiration_time = 365 * DAY_IN_SECONDS;
    $user = wp_get_current_user();
    $display_name = $user->display_name;
    $user_email = $user->user_email;
    $subject = "Application Viewed Again By: " . rand(0,1000000);
    $subject .= "$display_name";
    $msg = 'name & name,

    ';
    $msg .= "$display_name";
    $msg .= " (";
    $msg .= "$user_email";
    $msg .= ") ";
    $msg .= "just opened the page to begin their application again.

    The last time they viewed it was on: " ;
    $msg .= "$last_app_page_visit";
    $msg .= '

    The time is currently: ';
    $msg .= "$current_date_time";
    wp_mail( $to, $subject, $msg, $headers );
    unset( $_COOKIE['first_app_time'] );
    setcookie( 'first_app_time', $current_date_time, time() + $expiration_time );
    } else {
    $headers = 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
    $to ="email, email";
    $current_date_time = current_datetime()->format('m/d/Y g:i a');
    $expiration_time = 365 * DAY_IN_SECONDS;
    $user = wp_get_current_user();
    $display_name = $user->display_name;
    $user_email = $user->user_email;
    $subject = "name First Time View: " . rand(0,1000000);
    $subject .= "$display_name";
    $msg = 'name & name,

    ';
    $msg .= "$display_name";
    $msg .= " (";
    $msg .= "$user_email";
    $msg .= ") ";
    $msg .= "just opened the page to begin their application for the first time!" ;
    $msg .= '

    The time is currently: ';
    $msg .= "$current_date_time";
    wp_mail( $to, $subject, $msg, $headers );
    setcookie( 'first_app_time', $current_date_time, time() + $expiration_time );
    }
    }
    remove_action( 'application_notification' );
    }
    Thread Starter scottstarl

    (@scottstarl)

    Also I noticed it converts my spacing in the subject and email lines using < br / > to actual spaces when I paste it here, so that’s why it looks slightly off…

    Moderator bcworkz

    (@bcworkz)

    Still unclear how this is sending any emails ??
    add_action( 'application_notification' );
    should be
    add_action('init', 'application_notification');
    and thus to remove use
    remove_action('init', 'application_notification');

    I know this is all new to you, needing help to resolve what I see as silly errors is not a problem. The more important point though is that there must be other code sending emails if you’re passing only one arg to add_action() and still getting emails.

    FYI, copy/pasting exactly what code you are using, extra lines and plentiful comments is fine. Attempting to consolidate could confuse the problem. Just do not present extraneous code here that might occur before or after what’s germane to the problem at hand.

    I think what’s happening here is a race condition is introduced. The callback re-executes before PHP can remove the callback from the execution stack. Move the remove_action() line to the very first thing in the function declaration. Despite being removed, the rest of the function will still execute since it had already started.

    Thread Starter scottstarl

    (@scottstarl)

    Thank you for your patience, I’m going to crack this today. I am using SMTP for my emails by the way, it’s configured through the free version of the plugin: Admin and Site Enhancements (ASE). That was why I used the random number generator, to make sure it wasn’t my other website’s SMTP server causing the duplicates! The SMTP does not go through the plugins servers, it’s using a secondary website I own that I already had email addresses set up for using Office 365.

    I believe I can get this fixed today with what you’ve given me. I will update you in a bit when I have some more progress… I’ve been resorting to trying to have the php function activate when the button that opens that page is clicked instead since that’s the only way to navigate to the page… If that doesn’t work out I’m going to come back to having the function activate automatically then detect the page ID and see if it works.

    I will say though, it seems that the previous iteration of this code I was working on would fire as many emails as it could in about two minutes, then stop unless I started scrolling or otherwise having activity on the page that was referenced in the if command. I appreciate your continued help!

    Thread Starter scottstarl

    (@scottstarl)

    Also, will this forum redact personal email addresses when I post exact code?

    Thread Starter scottstarl

    (@scottstarl)

    Final version before bed, still having the same issue. Removed all plugins that relate to email, didn’t fix it. Installed a plugin so that the office 365 uses OAth and that didn’t seem to fix it either. Maybe an issue with cron? Not too sure… I tried using a sleep function to force a pause and allow the code to catch up (similar to how I would use AHK), but that didn’t seem to work.

    Something that I noticed that may be a clue to what’s going on: When I deactivate the snippet, then reactivate it later, even if it’s been an hour, the server will start sending old emails. It seems as if it’s creating a backlog, then when I use the code again it picks up where it left off, then proceeds to start packing more wp_mail into the log. I’ve been using code snippets (https://www.ads-software.com/plugins/code-snippets/) to put this into the functions.php, now I’m wondering if just the add_action should be there and the rest of the code should be somewhere else. The lack of experience really just forces you to hit a wall of forums and 1000 google searches.

    Here was the last version I had, still just the same issue of many duplicates (everything else I’m trying to do here works perfectly though). I only replaced the emails with “email” and names with “Name” for privacy reasons, everything else is the same. This last time I set the plugin to “Only run on site front-end” and left the priorty default at “10”. Didn’t notice any difference there. I want to agree with you on the race condition after researching what that is, but considering the backlog, it’s too sporadic with how many it sends for me to understand:

    // Begin notification loop - CHANGE NOTIFICATION NAME FOR NEW ITERATION
    add_action( 'init', 'application_notification' );
    
    	// Actions for notification loop - CHANGE NOTIFICATION NAME TO MATCH LOOP FOR NEW ITERATION
    	function application_notification() {
    
    	// Prevents additional looping without stopping current loop - CHANGE NOTIFICATION NAME FOR NEW ITERATION
    	remove_action( 'init', 'application_notification' );	
    
    		// Grabs the currents pages id - DO NOT CHANGE FOR NEW ITERATION
    		$postid = get_the_ID();
    			
    		// Do this if page id is correct - CHANGE PAGE NUMBER FOR NEW ITERATION
    		if( $postid = 1388 ) {		
    			
    			// Do this instead if cookie is not set - CHANGE COOKIE NAME FOR NEW ITERATION
    			if( !empty( $_COOKIE['jit_app_time'] ) ) {
    				
    				// Constant settings for all cases
    					// Date and time
    						// Time of visit - DO NOT CHANGE FOR NEW ITERATION
    						$current_date_time = current_datetime()->format('m/d/Y g:i a');
    
    					// Cookie settings
    						// How long the cookie lasts, the number is the amount of days - CHANGE LENGTH OF COOKIE IN DAYS FOR NEW ITERATION
    						$expiration_time = 365 * DAY_IN_SECONDS;
    
    					// User data
    						// Grabs the data for the user currently viewing the page - DO NOT CHANGE FOR NEW ITERATION
    						$user = wp_get_current_user();
    
    						// Full name of the user - DO NOT CHANGE FOR NEW ITERATION
    						$display_name = $user->display_name;
    
    						// Email of the user - DO NOT CHANGE FOR NEW ITERATION
    						$user_email = $user->user_email;	
    
    					// Email settings
    						// Where the email is sent, seperated by commas - CHANGE EMAIL ADDRESSES  FOR NEW ITERATION
    						$to = "email, email";	
    				
    				// Specific settings for this if only
    					// Email settings
    						// All are added together, use $subject .= for subsequent lines, values need their own line - CHANGE EMAIL SUBJECT FOR NEW ITERATION
    						$subject = 'J.I.T. First Time View:  ';
    						$subject .= "$display_name";
    
    						// All are added together, use $body .= for subsequent lines, values need their own line - CHANGE EMAIL BODY FOR NEW ITERATION
    
    							$body = 'Name and Name, ';
    						
    							$body .= "$display_name";
    							$body .= ' (';
    							$body .= "$user_email";
    							$body .= ') ';
    							$body .= 'just opened the page to begin their J.I.T. application for the first time!';
    						
    							$body .= ' The time is currently: ';
    							$body .= "$current_date_time";
    				
    					// Send email - DO NOT CHANGE FOR NEW ITERATION
    					wp_mail( $to, $subject, $body );
    			}	
    			// Do this if cookie is set - CHANGE COOKIE NAME FOR NEW ITERATION
    			elseif( !isset( $_COOKIE['jit_app_time'] ) ) {
    				
    				// Constant settings for all cases
    					// Date and time
    						// Time of visit - DO NOT CHANGE FOR NEW ITERATION
    						$current_date_time = current_datetime()->format('m/d/Y g:i a');
    
    					// Cookie settings
    						// How long the cookie lasts, the number is the amount of days - CHANGE LENGTH OF COOKIE IN DAYS FOR NEW ITERATION
    						$expiration_time = 365 * DAY_IN_SECONDS;
    
    					// User data
    						// Grabs the data for the user currently viewing the page - DO NOT CHANGE FOR NEW ITERATION
    						$user = wp_get_current_user();
    
    						// Full name of the user - DO NOT CHANGE FOR NEW ITERATION
    						$display_name = $user->display_name;
    
    						// Email of the user - DO NOT CHANGE FOR NEW ITERATION
    						$user_email = $user->user_email;	
    
    					// Email settings
    						// Headers - DO NOT CHANGE FOR NEW ITERATION	
    
    						// Where the email is sent, seperated by commas - CHANGE EMAIL ADDRESSES  FOR NEW ITERATION
    						$to = "email, email";	
    				
    				// Specific settings used when the last if is false only
    					// Cookie settings 
    						// Timestamp stored in the most recent cookie - CHANGE COOKIE NAME FOR NEW ITERATION
    						$last_app_page_visit = $_COOKIE['jit_app_time'];
    
    					// Email settings
    						// All are added together, use $subject .= for subsequent lines, values need their own line - CHANGE EMAIL SUBJECT FOR NEW ITERATION
    						$subject = 'J.I.T. Viewed Again By: ';
    						$subject .= "$display_name";
    
    						// All are added together, use $body .= for subsequent lines, values need their own line - CHANGE EMAIL BODY FOR NEW ITERATION
    					
    							$body = 'Name and Name, ';
    							$body .= "$display_name";
    							$body .= ' (';
    							$body .= "$user_email";
    							$body .= ') ';
    							$body .= 'just opened the page to begin their J.I.T. application again. The last time they viewed it was on: ';
    							$body .= "$last_app_page_visit";
    						
    							$body .= ' The time is currently: ';
    							$body .= "$current_date_time";
    				
    					// Send email - DO NOT CHANGE FOR NEW ITERATION
    					wp_mail( $to, $subject, $body );
    				
    					// Update cookie settings
    						// Force cookie to expire so browser will remove it - CHANGE COOKIE NAME FOR NEW ITERATION
    						setcookie( 'jit_app_time', $current_date_time, time() + $expiration_time );	
    						// Remove cookie timestamp as back so we can reset it - CHANGE COOKIE NAME FOR NEW ITERATION
    						unset( $_COOKIE['jit_app_time'] );
    			}	
    			// Retires and other arguments by doing nothing - DO NOT CHANGE FOR NEW ITERATIONS
    			else{}
    			
    			// Set the cookie with the current time - CHANGE COOKIE NAME FOR NEW ITERATION
    			setcookie( 'jit_app_time', $current_date_time, time() + $expiration_time );		
    		}
    	}
    Thread Starter scottstarl

    (@scottstarl)

    Oh and the backlog of emails I referenced, they’re not pretyped, its a log of code. I know that because it will send blank values where $user should be since I’m not on the page anymore. That leads me to believe it is running when I’m not on the page rather than simply sending emails late that were already generated. If I just let the code run for an hour, it eventually stops sending emails, then reactivating it will start dumping the backlog…

    Moderator bcworkz

    (@bcworkz)

    Also, will this forum redact personal email addresses when I post exact code?

    No, you need to manually obfuscate personally identifying information (PII) before posting. Moderators will remove PII when we happen to see it, but it’s usually well after being published, after scraper bots may have possibly already found the PII. Moderators will not remove any information unless it presents a legal or security issue. It often happens that people want non-sensitive information removed such as their domain name. We cannot do this, we’re all volunteers and don’t have the resources to remove on demand anything someone’s unhappy about which they didn’t catch in their 30 minute edit window.

    Your code has a couple minor flaws that would cause double emails, but should not be more than that.

    // Do this instead if cookie is not set - CHANGE COOKIE NAME FOR NEW ITERATION
    if( !empty( $_COOKIE['jit_app_time'] ) ) {
    // Do this if cookie is set - CHANGE COOKIE NAME FOR NEW ITERATION
    elseif( !isset( $_COOKIE['jit_app_time'] ) ) {

    In both of these, you do not want to use the negation operator !. It’s saying “if not empty”, “if is not set”. Note that empty and set are not exactly reciprocal. A zero or false value is “set”, but is “empty”. Consider using empty($_COOKIE['jit_app_time']) in one and ! empty($_COOKIE['jit_app_time']) in the other.

    I tested your code so revised on my test site, also changing the page ID of course. It works as expected for me, one email per page load. You aren’t doing anything to filter out bot requests, could bot traffic be the cause of the extra messaging? I think you’d want to only send emails about logged in users. You should check is_user_logged_in() before doing anything.

    In real world usage, how many notifications are you expecting? Unless it’s just a few, wouldn’t it make more sense to simply log the visits? Of course the normal server access log does this anyway, but it doesn’t discriminate. It will not indicate first time or return, nor WP user data. A bespoke logging scheme would make sense if the email volume gets to be too much.

    Thread Starter scottstarl

    (@scottstarl)

    Can’t be bot activity, since I’m using this website as an LMS everything requires the correct membership to access, which they aquire via admin approval! I will still add the is_user_logged_in() check as another precaution to avoid future bugs.

    Thank you for the insight, I had no idea that ! would negate something…. I was using it in CSS style in a frowned upon way last week:”!important”. I 100% misunderstood how it works in PHP!

    I feel very optimistic about using the changes you suggested. Will test today and report back with results!

    Thread Starter scottstarl

    (@scottstarl)

    “In real world usage, how many notifications are you expecting? Unless it’s just a few, wouldn’t it make more sense to simply log the visits? Of course the normal server access log does this anyway, but it doesn’t discriminate. It will not indicate first time or return, nor WP user data. A bespoke logging scheme would make sense if the email volume gets to be too much.”

    Since this is a private site for training employees, it’s crucial to understand when they hit a certain checkpoint so they can be reached out to. Relying on leaving a “reach out to so and so” message really just doesn’t do the trick.

    I implemented the changes, no luck though. Still many emails, let me ensure that I didn’t make a mistake. I will dig into this again at the end of the when I have some time!

Viewing 15 replies - 1 through 15 (of 27 total)
  • The topic ‘Emailing Logged In Users Upon Page Visit’ is closed to new replies.