WordPress Avoid Running save_post Functions on Trashed Posts

This may be one of those things that everyone knows but it was new to me. I’m also duplicating the information I found in the StackOverflow post because I think it’s good to have information in multiple places where it might be found by other people. Additionally, writing the post makes it easy for me to find later when I forget and the act of writing the post helps get it stuck in my own head. With all of that as the lead up . . .

A common way to trigger events in WordPress is the save_post action. It runs any time the post is created, published, or updated. What I found out though was that it also runs when you try to delete the post. That makes sense. It is an update and it’s no big deal if the function is relatively small and/or if you’re not trying to get rid of a ton of posts. My current experiment had both a fairly involved function and a couple hundred posts I wanted deleted.

Luckily, I found this post on StackOverflow.

Now I can set a simple check at the beginning of the function that looks to make sure it’s the right post type (site) and it’s a trashed post. In either of those cases the function gets skipped.


function siteUpdateData($post_id, $post, $update){
   $post_type = get_post_type($post_id);	
      if ( "site" != $post_type ||  'trash' === get_post_status( $post_id )  ) {    	
    	return;
    } 
//the rest of the function if the post is live and of the post type site . . . 
}

add_action( 'save_post', 'siteUpdateData', 10, 3);

Comments on this post

No comments.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Trackbacks and Pingbacks on this post

No trackbacks.

TrackBack URL