user254153
user254153

Reputation: 1883

WordPress "save_post" call only on save post not on update

I am trying to send post data to third-party services when the post is saved via API. I am using hook add_action( 'save_post', [$this, 'save_post_callback'], 100, 3); but this hook seems to be called in update post as well as post-new.php in admin panel. So to get rid of running this hook in post-new.php, I have checked the $_POST request but I am not able to filter the update post since I want to call API only in save the post, not in an update.

There seems to be the third parameter in callback function $update but it's not working either. Below is my code that needs to be called only in save a post but it's not working. Any help would be greatly appreciated.

 function save_post_callback( $post_id, $post, $update ) {
    // (!$update) => this doesnot seems to work
    if(!empty($_POST) && $post->post_type == "post"){
        //run only when save post
    }
}

Upvotes: 1

Views: 3126

Answers (3)

Otávio C A Serra
Otávio C A Serra

Reputation: 147

From StackExchange here like @jody told above. So, I changed this reffer and made one solution for insert, update and delete actions:

// Flag to identify whether this is a new post or an update or trash
$action = '';

// Find out which operation is being done by the save_post hook: add, update, delete.
$is_new = $post->post_date === $post->post_modified;
if ( $is_new && $post->post_status === 'publish' ) {
    $action = 'add';
} else if ( $post->post_status === 'publish' ){
    $action = 'update';
} else if ( $post->post_status === 'trash' ){
    $action = 'delete';
}

Upvotes: 0

Ali Qorbani
Ali Qorbani

Reputation: 1263

simple way is to check if _wp_http_referer last part is post-new.php or not.

here is a simple code

function save_post_callback($post_id, $post, $update)
{
    // (!$update) => this doesnot seems to work
    if ( ! empty($_POST) && $post->post_type == "post" ){
        $end = explode('/', $_POST[ '_wp_http_referer' ]);
        $end = end($end);
        if($end == 'post-new.php'){
            //echo 'it is new post';exit();
            //do what you want here.
        }
    }
}

Upvotes: 2

Jody
Jody

Reputation: 39

From StackExchange here. It looks like a clever way is to compare the post_date & post_modified to determine it is a new post.

$is_new = $post->post_date === $post->post_modified;

if ( $is_new ) {
    // first publish
}

Upvotes: 1

Related Questions