save_post action only when creating a new post

The save_post action also passes three parameters to your callback, one of which being $update which denotes whether the post being saved is an existing post or not. /** * Save post metadata when a post is saved. * * @param int $post_id The post ID. * @param post $post The post object. * @param … Read more

save_post action firing before I publish / save the post

A draft or “blank” is saved as soon as you start to create a new post. Those new posts have the post_status of auto-draft. Check for that to prevent your callback from firing on those “blank” post saves. function update_test( $post_id, $post ) { if (isset($post->post_status) && ‘auto-draft’ == $post->post_status) { return; } update_post_meta($post_id, ‘copied’, … Read more

get post meta before it is updated (during SAVE_POST)

save_post Runs whenever a post or page is created or updated, which could be from an import, post/page edit form, xmlrpc, or post by email. Action function arguments: post ID and post object. Runs after the data is saved to the database. above paragraph is quoted from WP Codex. so you cannot use this hook … Read more

Action hook ‘save_post’ triggered when deleting posts

It’s probably easiest to just check the post status within your function. Untested: add_action( ‘save_post’, ‘rewrite_post’, 10, 2 ); function rewrite_post( $post_id ) { if ( ‘trash’ != get_post_status( $post_id ) ) { remove_action( ‘save_post’, ‘rewrite_post’ ); $title = preg_replace( ‘/\_/’, ‘ ‘, get_the_title( $post_id ) ); $my_post = array( ); $my_post[‘ID’] = $post_id; $my_post[‘post_title’] … Read more

$update is always true in save_post

So appreciate this is a bit late but I was having the exact same issue, the $update parameter is almost completely useless if you want to check whether it is a new post or not. The way I got around this was to compare the $post->post_date with $post->post_modified. Full code snippet below. add_action( ‘save_post’, ‘save_post_callback’, … Read more

How to avoid infinite loop in save_post callback

You can remove the callback from the save_post hook, update the post and then re-add the call back to the hook. The Codex gives an example. add_action(‘save_post’, ‘wpse51363_save_post’); function wpse51363_save_post($post_id) { //Check it’s not an auto save routine if ( defined(‘DOING_AUTOSAVE’) && DOING_AUTOSAVE ) return; //Perform permission checks! For example: if ( !current_user_can(‘edit_post’, $post_id) ) … Read more

Check for update vs new post on save_post action

Since WordPress version 3.7. – IIRC – the save_post hook – more information about the hook and its usage at Code Reference: save_post and Codex: save_post – has a third parameter $update which can be used to determine just that. @param     int               $post_ID     Post ID. @param     WP_Post     $post          Post object. @param … Read more