1

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') { ...)

2

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

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.