phpwordpresspost-meta

Wordpress post update not updating postmeta by wordpress hook


I want to update postmeta value for a post by wordpess hook but i am not able to update it. Here is my code,

function check_values($post_ID, $post_after, $post_before){

     $oldFob = get_post_meta( $post_ID, 'price', true);
     if($oldFob){
         update_post_meta( $post_ID, 'price', 500);
     }else{
         add_post_meta( $post_ID, 'fob-price', 500 , true);
     }
   }

 add_action( 'post_updated', 'check_values', 10, 3 );

When I put die soon after update_post_meta, and check db, it works but after coming back to edit post page, it reverts.

Basically it is updating post meta but after it, there is another default wordpress function run and reset it to old value.

Any expert suggestion, why its happening so??


Solution

  • The problem is because the hook post_updated is triggered before the metas of the post is actually saved.

    So basically you update the meta of the post, then the post gets updated with the meta values submitted in the request right after that.

    To solve this, you can use the save_post hook with a high number for the priority to have the hook run last:

    add_action('save_post', function ($post_ID) {
        $oldFob = get_post_meta( $post_ID, 'price', true);
    
        if ($oldFob) {
            update_post_meta( $post_ID, 'price', 500);
        } else {
            add_post_meta( $post_ID, 'fob-price', 500 , true);
        }
    }, 100);
    

    For more information: https://codex.wordpress.org/Plugin_API/Action_Reference/save_post