PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, March 2, 2022

[FIXED] Save Post and Add Post Meta Executing Twice

 March 02, 2022     function, hook, php, wordpress     No comments   

Issue

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); 
        }    
   }    
}

Solution

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' ) );
    }
}


Answered By - Howard E
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing