I am using save_post for a function to send an email when a post is updated by a user. This is firing twice and I am aware this is due to the post revisions and autosaves.

I have tried to prevent this from happening by wrapping my wp_mail within a conditional statement but this still fires twice. What adjustments do I need to make to ensure this only fires once when a user updates the post?

function updated_search_notification($post_id)
{

    $post_type = get_post_type($post_id);
    if ($post_type === 'utility-search') {

        if ((wp_is_post_revision($post_id)) || (wp_is_post_autosave($post_id))) {
            // post is autosave
        } else {

            // Message Variables
            $siteurl                 = get_option('siteurl');
            $post_url="" . $siteurl . '/wp-admin/post.php?post=" . $post_id . "&action=edit';
            $new_search_name="";
            //$new_search_email = get_option( 'new_search_email' );
            $new_search_email="[email]";
            $utility_search_customer="";
            $subject="Your search has been updated";

            // Message Contents
            $message = "[Message Contents]";


            // Send Email    
            wp_mail($new_search_email, $subject, $message);
        }
    }


}
add_action('save_post', 'updated_search_notification', 10, 3);

4 s
4

First, you can use this hook to target only one custom type:
https://developer.wordpress.org/reference/hooks/save_post_post-post_type/

This hook (and save_post) is called the first time when you click on “new …” and then the hook is called with $update = FALSE.

Then to send e-mail only when the object is updated, you can test $update like this:

const UTILITY_SEARCH_POST_TYPE = "utility-search";


add_action("save_post_" . UTILITY_SEARCH_POST_TYPE, function ($post_ID, $post, $update) {

    if (wp_is_post_autosave($post_ID)) {
        return;
    }

    if (!$update) { // if new object
        return;
    }


    // preparing e-mail
    ...

    // sending e-mail
    wp_mail(...);


}, 10, 3);

Leave a Reply

Your email address will not be published. Required fields are marked *