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);

firstly, you can use this hook to target only one custom 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)) {

    if (!$update) { // if new object

    // preparing e-mail

    // sending e-mail

}, 10, 3);
  • This worked perfectly, thank you. Also, a nice reminder for the use of const too! – Ben H Jul 15 '18 at 17:36

Try this piece of code inside your function:

if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;

Alternatively, you can use publish_post hook. If you just want to trigger this function when the post status is publish.

  • Thank you for the suggestion. When using this method and clicking the 'Update' button on a post, I still get two emails come through. I have a separate function for when a post is published. – Ben H Jul 15 '18 at 11:34
  • Did you put code on right spot? Did you try publish_post hook? – Atlas_Gondal Jul 15 '18 at 14:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.