Joseph Adegbola
Joseph Adegbola

Reputation: 59

Save Post and Add Post Meta Executing Twice

I'm trying to add or update two post meta on saving a post. Add if it's a new post and update if existing, but this function creates four in the database instead of two meta.

add_action( 'save_post',  'add_rewards');
global $WCFM, $WCFMmp;
function add_rewards ($product_id){
        if($product_id){
            $post_type = get_post_type($product_id);
            if($post_type == 'product'){
                $product = wc_get_product( $product_id );
                $reg_price = $product->get_regular_price();
                $sal_price = $product->get_sale_price();
                $pric = $product->get_price();
                add_post_meta($product_id,'main_reward', $reg_price); 
                add_post_meta($product_id,'sub_reward', $sal_price); 
        }    
   }    
}

Upvotes: 2

Views: 1233

Answers (1)

Howard E
Howard E

Reputation: 5639

As it explains in the save_post manual, you should use save_post_{$post->post_type} which minimizes the save_post calls on other post types. It's also a good idea to check for autosave.

Also, if you use update_post_meta instead of add_post_meta you'll end up with only one instance of each. As it explains in the manual for that function, it says:

If the meta field for the post does not exist, it will be added and its ID returned. Can be used in place of add_post_meta().

add_action( 'save_post_product', 'so71077799_add_rewards', 99, 1 );
function so71077799_add_rewards( $product_id ) {
    // Check to see if we are autosaving, if so, exit.
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
        return;
    }
    if ( isset( $_POST['_regular_price'] ) ) {
        update_post_meta( $product_id, 'main_reward', number_format( floatval( $_POST['_regular_price'] ), '2' ) );
    }
    if ( isset( $_POST['_sale_price'] ) ) {
        update_post_meta( $product_id, 'sub_reward', number_format( floatval( $_POST['_sale_price'] ), '2' ) );
    }
}

Upvotes: 2

Related Questions