Function executing twice on post first publish hook

I am hooking into save_post when a post is published for the first time. The function will send off to an API to shorten the URL. Everything works good, but the problem is that it’s generating 2 links when only one is needed. I believe this is because it’s triggering too early once the publish button is clicked.

One of the links is including the ?post_type=news which is not needed. This is the current CPT I’m posting from.

Also, when trashing the post, the function will trigger again.

function update_test( $post_id, $post ) {
if ( isset($post->post_status) && ‘auto-draft’ == $post->post_status ) {
return;
}
$post_url = esc_url( get_permalink ( $post_id ) );
$api_key = esc_attr ( get_option ( ‘polr_settings_api_key’ ) );
$host_url = esc_url( get_option( ‘polr_settings_host’ ) );
$shortenedurl = file_get_contents( $host_url . ‘/api/v2/action/shorten?key=’ . $api_key . ‘&url=’ . $post_url . ‘&is_secret=false’ );
update_post_meta( $post_id, ‘polr_shortened_url’, esc_url_raw ( $shortenedurl ) );
}
add_action( ‘save_post’, ‘update_test’, 1, 2 );

Read more here:: Function executing twice on post first publish hook

Leave a Reply

Your email address will not be published. Required fields are marked *