How do I compare old meta what was already stored in the database with the new meta data what was just set by the user?

For example if you want to keep track of how many times a button is clicked. Let's say the button has been clicked 2 times before the user started editing the post, after editing the post the user clicked the button 3 times so the new value of post meta what tracks the amount of times that the button was clicked will now have the value 5. However I want to know what the difference is between the old value 2 and new value 5, obviously that's 3. Unfortunately I'm unable to calculate this value since I need the new value and I'm not sure how to correctly lookup the new value.

What I tried so far is using the hook wp_insert_post this hook fires before the post is inserted/updated. However the hook only includes the following parameters:

  • The post ID.
  • The NEW WP_Post object, which doesn't include post meta.
  • A boolean value what tells you if the post is updated or inserted.

This is obviously not all the data I need. However I'm able to read the old data because I know the post ID and with that I can use get_post_meta() to get the old value of the meta. Anyway I won't be able to lookup the new post meta value with this function.

The straightforward solution would be reading the new values of the post meta from the $_POST variable, but this seems like a neat little hack to me. Are there any WordPress hooks or functions made exclusively for this? What would be the best approach to achieve this?

  • I can't think / don't know another way than checking the $_POST variable. It make sense to check the $_POST variable because you are handling a post request (escaping data etc) before doing anything like saving the values etc – Laxmana Feb 6 '17 at 13:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.