save_post
being called multiple times is expected behavior, but because of how it’s used, you may not always want your code to execute until the user actually clicks on the save button. Like you have mentioned above regarding your requirement.
So you can check the current page ( i.e post-new.php
) in the wp-admin and can put conditions based upon that. Here is how you can implement.
global $pagenow;
// Checking for coupon active option.
if ( $coupon_status ) {
if ( checked( '1', $coupon_status, false ) )
$active = checked( '1', $coupon_status, false );
}
if ( 'post-new.php' == $pagenow ) {
$active="checked";
}
========== Or you can check this too ============
if( ! ( wp_is_post_revision( $post_id) && wp_is_post_autosave( $post_id ) ) ) {
// do the work that you want to execute only on "Add New Post"
} // end if
It’s worth understanding Why It Happens & what’s goes on behind the scenes of save_post:
- Posts go through an autosave process whenever it’s created and whenever it’s being drafted. As such, save_post is actually fired multiple times while a user is drafting a post.
- When the user clicks “Save” or “Publish” the function fires thus kicking off yet-another-round of the function being called.
- Finally, it’s worth noting the the edit_post function fires once, but only when the user has actually edited an existing post.
–