Exclude trash from save_post

I have a function which processes custom metabox data on saving my custom post type:

add_action('save_post_customtypehere','myown_save_customtype_fn');
function myown_save_customtype_fn($ID) { ... }

However, the function also runs when I trash items within this CPT (I guess it's effectively saving the post to change post_status to trash). Without the metabox being present, my function ends up clearing things like post_name (not great if I need to restore from trash!).

I have two thoughts but can't quite get across the finishing line with them:

1) In order to update post data I use remove_action() and add_action() again around wp_update_post(array('post_key'=$sanitized_form_input)) - as per the codex instructions, this is required to avoid an infinite loop. Could there be a similar way of excluding from a trash_post action (I already tried remove_action('trash_post','myown_save_customtype_fn' immediately after the original add_action line).

2) Is there something I can use in a conditional within myown_save_customtype_fn (along the lines of if (current action!='trash_post') { ...)

Topic save-post trash actions Wordpress

Category Web


The following helps for skipping the restore option as well as the trash option:

<?php
add_action( 'save_post_POSTTYPEHERE', function( $post_ID, $post, $update ) {
    
    /* do not save meta on trash/untrash event */
    if(
        isset($_REQUEST['action']) &&
        ( $_REQUEST['action'] == 'trash' || $_REQUEST['action'] == 'untrash')
    ){
        return;
    }

    /** do your stuff **/
    
}, 10, 3 );
?>

save_post gets fired, once the post is saved. We get the current post object as the second parameter. So we can check, if the current post status is trash:

<?php
add_action( 'save_post', function( $post_ID, $post, $update ) {
    if ( 'trash' === $post->post_status ) {
        return;
    }

    /** do your stuff **/
}, 10, 3 );
?>

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.