Home > Mobile >  Don't run code during autosave in save_post on Wordpress
Don't run code during autosave in save_post on Wordpress

Time:10-31

I have a custom post type in Wordpress and I want to run a custom code when the post is published. Not during the autosave or update.

function send_notification($post_id, $post){

    $is_autosave = wp_is_post_autosave( $post_id );
    $is_revision = wp_is_post_revision( $post_id );

    if ( $is_autosave || $is_revision ) {
        return;
    }

    if (get_post_type( $post_id ) == 'vip_post') {
         send_message($post->post_content);
    }
}

add_action('save_post', 'send_notification', 10, 2);

However, I found that the function send_message is getting triggered multiple times while I am writing something in the Post Editor and before I click on publish button.

CodePudding user response:

You can use did_action to check action already called? try the below code.

function send_notification($post_id, $post){

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

    $is_autosave = wp_is_post_autosave( $post_id );
    $is_revision = wp_is_post_revision( $post_id );

    if ( $is_autosave || $is_revision ) {
        return;
    }

    $times = did_action('save_post');
    if( $times === 1 ){
        if (get_post_type( $post_id ) == 'vip_post') {
             send_message($post->post_content);
        }
    }

}
add_action( 'save_post', 'send_notification', 10, 2 );

An alternative version of the above code with an early return.

function send_notification($post_id, $post){

    if ( did_action( 'save_post' ) > 1 ){
        return; 
    } 

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

    $is_autosave = wp_is_post_autosave( $post_id );
    $is_revision = wp_is_post_revision( $post_id );

    if ( $is_autosave || $is_revision ) {
        return;
    }

    if (get_post_type( $post_id ) == 'vip_post') {
         send_message($post->post_content);
    }

}
add_action( 'save_post', 'send_notification', 10, 2 );

Also, You can remove your action using the remove_action hook. once your function is called.

function send_notification($post_id, $post){

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

    $is_autosave = wp_is_post_autosave( $post_id );
    $is_revision = wp_is_post_revision( $post_id );

    if ( $is_autosave || $is_revision ) {
        return;
    }

    if (get_post_type( $post_id ) == 'vip_post') {
         send_message($post->post_content);
    }

    remove_action('post_save', 'send_notification');

}
add_action( 'save_post', 'send_notification', 10, 2 );

OR

You can completely disable it by deregistering the script using wp_deregister_script. try below code.

add_action( 'admin_init', 'disable_autosave' );
function disable_autosave() {
    wp_deregister_script( 'autosave' );
}
  • Related