I want to do the following in a plugin: - hook to untrash_postwith a custom function - do some checking inside custom function - cancel actual post restoring (untrashing)

I've tried with remove_action but doesn't seem to work. Can you point me into the right direction?

Code sample:

add_action( 'untrash_post', array( __CLASS__, 'static_untrash_handler' ) );


public static function static_untrash_handler( $post ) {

// check stuff

// prevent post from being restored. How ?


Should I return something to 'break the cycle' ?

Thank you in advance!

  • Can you just update the post status to trashed in that hook? What does it report as the status in the handler?
    – jgraup
    Feb 26 '16 at 16:44
  • You can't set it to trashed in that hook, because it'll just get immediately set back, but maybe you can hook untrashed_post instead, which runs immediately after it's untrashed instead of before. See it in source here.
    – Milo
    Feb 26 '16 at 16:48

its a little clumsy but you could combine what you are already doing with the 'untrashed_post' hook which fires after the post has been untrashed

here are the rough steps:

  • use 'untrash_post' hook to do your checking (like you are now)
  • if you need to cancel the untrash, store a flag in post meta with ie. update_post_meta( $post_id, 'keep_trashed', true );
  • use 'untrashed_post' to check if the post should be retrashed with get_post_meta( $post_id, 'keep_trashed', true );
  • if so, use wp_trash_post( $post_id ); to retrash the post
  • dump the post meta delete_post_meta( $post_id, 'keep_trashed' );
  • I'm thinking at optimization and this solution will add more queries. It will work but with a cost :) Thanks!
    – SXN
    Feb 26 '16 at 17:10
  • agreed .. i think it would be better if the parent function 'wp_untrash_post' actually checked for a return value from the 'untrash_post' hook and provided an option to exit the function at that point. That said unless your users will be doing this a lot, its not such a big optimization issue.
    – locomo
    Feb 26 '16 at 17:29
  • Indeed, that I was expecting to be the behavior but untrashed_post hook will do the trick!
    – SXN
    Feb 26 '16 at 17:31

untrash_post fires before the untrashing happens. If you want to undo the untrashing, you should use the untrashed_post action which fires after it.

  • Oh yes, this is a solution but I was thinking at something more 'optimized' since this will be redundant: untrash post -> check stuff -> trash post. This means more queries to the WP database. Beside this, it will do it. Thank you!
    – SXN
    Feb 26 '16 at 17:07
  • you can always try make checks before wp_untrash_post is called to prevent it, but it is much harder to cover all possible paths Feb 26 '16 at 17:27

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.