Skip to content
Read For Learn
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP

update post meta value with other post meta value

@Jawequo-

You need to know how WordPress works in order to understand the answer to your question. There are a ton of functions, and they all call each other to do their job. As the best way to learn about coding is to read code, I’ll provide links in walking you thru how post meta is made, updated, and deleted. In my doing this, you’ll be able to better find answers to your questions in the future.

Let’s say you create a post using wp_insert_post(). If you trace this function, you’ll see the meta data for the post is inserted on line 4511 of the code by way of the update_post_meta() function, which, in turn, calls update_metadata() to do all the heavy lifting. If the metadata does not exist (which it doesn’t at this point as we’re creating a brand new post), add_metadata() will be called on line 250 of the code to insert it into the database. Ok, cool, now we know how a post and its metadata is created.

Later on, let’s say you update that same post using wp_update_post(). If you trace this function, you’ll see that wp_insert_post() is called on line 4788 of the code. As we’ve already traced this function, we know how a post and its metadata is updated (and inserted if it doesn’t exist). Ok, cool, now we know how a post and its metadata are updated.

At some point in time, you get tired of the post, so you delete it using wp_delete_post(). If you trace this function, you’ll see that the metadata gets deleted by way of delete_metadata_by_mid() on line 3446 of the code. Ok, cool, now we know how a post and its metadata are deleted.

Let’s now say that you want to just screw around with the metadata of an existing post. You can add meta data by way of add_post_meta(). If you trace this function, you’ll see that add_metadata() is called to do all the heavy lifting. To update existing metadata, you call update_post_meta(), which we already traced above. To delete metadata from a post, we call delete_post_meta(), which invokes delete_metadata() to do its heavy lifting. If you take a good look at delete_post_meta(), you’ll see that it is just about identical to delete_metadata_by_id() in terms of the order of the hooks and method by which the metadata is deleted. Ok, cool, now we know how to manipulate individual meta of a post without having to update the entire post itself.

It was important to explain all of this because you must have a working understanding of how post meta is updated. And, if you traced the code along with me, you’ll have seen those huge blocks of comments above the apply_filters() and do_action() functions. Those are called hooks, and the way WordPress notifies us that if we want to do something, that notification is our chance.

So, if you want to updates a piece of metadata when WordPress manipulates metadata, we can use one of the hooks described in add_metadata(), update_metadata(), or delete_metadata() (which are identical to those in delete_metadata_by_id()). So, let’s start with adding metadata after metadata is added using the added_{$meta_type}_meta hook hook. If you trace down from wp_update_post() (or one of the other related functions above) you’ll see that $meta_type = "post", so the hook we’ll use is add_post_meta:

add_action('added_post_meta', 'mort_metadata_changed', 10, 4);

As you are writing code for WordPress, I must assume that you already know about hooks. In case you don’t here’s a nice little tutorial about them. The hooks for after metadata is updated or deleted from a post are nearly identical to the added hook: updated_{$meta_type}_meta (update_post_meta) and deleted_{$meta_type}_meta (delete_post_meta). So, the hooks we want to use are nearly identical as well.

add_action('updated_post_meta', 'mort_metadata_changed', 10, 4);
add_action('deleted_post_meta', 'mort_metadata_changed', 10, 3);

Notice that deleting only needs the first three parameters to be sent to the mort_metadata_changed function. This is because the fourth parameter (the new meta value) is empty as the metadata would have been deleted. Let’s now create a function for these hooks to call.

function mort_metadata_changed($meta_id, $object_id, $meta_key, $meta_value=NULL) {
    // WordPress just did something with metadata.  Now, its our turn to do
    // something before WordPress continues on its merry way!
}

Notice the final parameter, $meta_value, has a default of NULL. By checking this, we will be able to tell if the function was called via the delete_post_meta hook or not. Importantly, however, take notice that we have interjected ourselves into the inner-workings of WordPress: every time a post’s metadata is updated, the mort_metadata_changed() function will execute.

With the information you have obtained by reading the notes above each hook in the code, you now know what each variable contains at the time it is passed to mort_metadata_changed(). Just in case you’re lost, try this on for size:

/**
 *  This will be called every time post metadata changes.
 *
 *  @param  int[]   $tmp         The meta IDs, which we won't use.
 *  @param  int     $post_id     The ID of the post whose metadata was changed.
 *  @param  string  $meta_key    The name of the meta data changed.
 *  @param  string  $meta_value  New value of the metadata.  `delete_post_meta`
 *                                only passes the first three parameters, so
 *                                the `NULL` default value can be checked to
 *                                determine if the change is a deletion of the
 *                                post's metadata.
 */
function mort_metadata_changed($tmp, $post_id, $meta_key, $meta_value=NULL) {
    // Did the post meta we're looking for change?
    if(get_post_type($post_id) !== 'listing'
    || get_post_status($post_id) !== 'publish'
    || $meta_key !== 'y'
    ) {
        // Nope. Something other than `y` of a published listing changed.
        return;
    }
    // Validation was passed.  Time to do the mimic.
    if(is_null($meta_value)) {
        // Metadata deleted.
        delete_post_meta($post_id, 'x');
    } else {
        // Metadata added/updated.
        update_post_meta($post_id, 'x', $meta_value);
    }
}

As for where to put this code, I again assume you know how to get your code to run.
But if you don’t, here’s a nice tutorial on the subject.

Related Posts:

  1. How do I retrieve the slug of the current page?
  2. Most efficient way to get posts with postmeta
  3. Get posts by meta value
  4. Explanation of update_post_(meta/term)_cache
  5. How to extract data from a post meta serialized array?
  6. How to save an array with one metakey in postmeta?
  7. WordPress is stripping escape backslashes from JSON strings in post_meta
  8. How can I get the post ID from a WP_Query loop?
  9. Check if Post Title exists, Insert post if doesn’t, Add Incremental # to Meta if does
  10. How to update_post_meta value as array
  11. Adding meta tag without plugin
  12. What’s the point of get_post_meta’s $single param?
  13. What is the different between an attachment in wp_posts and an attachment in wp_postmeta?
  14. How to edit a post meta data in a Gutenberg Block?
  15. Sanitizing integer input for update_post_meta
  16. post formats – how to switch meta boxes when changing format?
  17. Execute action after post is saved with all related post_meta records (data)
  18. Lack of composite indexes for meta tables
  19. Get a single post by a unique meta value
  20. if get_post_meta is empty do something
  21. How we get_post_meta without post id
  22. How get post id from meta value
  23. What is the code to get the download link for a product in WooCommerce?
  24. Safe to delete blank postmeta?
  25. advanced custom fields update_field for field type: Taxonomy
  26. update_post_meta not saving when value is zero
  27. Content hooks vs User hooks
  28. Meta compare with date (stored as string) not working
  29. Trying to get custom post meta through Jetpack JSON API [closed]
  30. How to update/insert custom field(post meta) data with wordpress REST API?
  31. Restrict post edit/delete based on user ID and custom field
  32. get_post_meta returning empty string when data shows in the database
  33. publish_post action hook doesn’t give post_meta_data
  34. Remove WordPress.org Meta link
  35. Remove post meta keys
  36. How to access the post meta of a post that has just been published?
  37. Why time functions show invalid time zone when using ‘c’ time format?
  38. Why is get_post_meta returning an array when I specify it as single?
  39. How to update/delete array in post meta value?
  40. How to get all term meta for a taxonomy – getting term_meta for taxonomy
  41. Adding an assisting editor box to Post page
  42. delete unused postmeta
  43. Should I sanitize custom post meta if it is going to be escaped later?
  44. Add post meta based on another post meta value before publish post
  45. How do I retrieve multi-dimensional arrays from the wp_postmeta table, & display on a website?
  46. Front-end update_post_meta snippet displays white screen?
  47. Query between two meta values?
  48. Save both current and new version of post meta
  49. Get Advanced Custom Fields values before saving [closed]
  50. Give extra post-meta to RSS feeds
  51. How to get meta value in wp_attachment_metadata
  52. WP REST API “rest_no_route” when trying to update meta
  53. Clean up output added via wp_head()
  54. List posts under meta_value heading
  55. Why am I getting an infinite loop with have_posts?
  56. get_post_meta – get a single value
  57. delete value 0 in post meta [closed]
  58. Can I safely delete a record, manually, in the wp postmeta table?
  59. How to store post meta in an array?
  60. What action hook updates post meta?
  61. Can’t translate the post meta data (Date) in another language
  62. get_post_meta / update_post_meta array
  63. adding a URL to a post meta
  64. Exclude a category from the filed under list
  65. Short of raw SQL, can I query for multiple attachment metadata that have a given array key?
  66. How do I access post meta data when publishing a new post in Gutenberg?
  67. update_post_meta() not working when used with WordPress action
  68. Using Advanced Custom Field (ACF) to insert meta description on each page
  69. Triple meta_key on custom SELECT query
  70. get_post_custom()
  71. Adding meta data to an attachment post
  72. update_post_meta not adding anything.(Nor add_post_meta)
  73. loop through all meta keys with get_post_meta
  74. Get posts by meta value with date
  75. How to add meta tag to wordpress posts filter?
  76. Are multiple values from get_post_meta guaranteed to be ordered?
  77. Identifying Importer Posts
  78. Get updated post meta on save_post action?
  79. Get post from meta_key and meta_value
  80. Add a post metadata if only the key and value does not exist
  81. get_post_meta returns bool(false)
  82. How metadata API works?
  83. Correct processing of `$_POST`, following WordPress Coding Standards
  84. Metabox Data not being saved [closed]
  85. How can I get values using key in Carbon Fields from Multiselect?
  86. Delete post meta conditionally after save post
  87. How to sanitize post meta field value?
  88. Problem With Order Item Meta In Woocommerce
  89. Job of meta_key meta_value fields in database tables
  90. WordPress Action Hooks and Post ID?
  91. Post IDs missing on delete_postmeta action hook
  92. How to store Gutenberg ColourPicker RGBA as metadata
  93. Options to get my custom post type metadata via the WordPress API
  94. Is it possible to update a post meta field through REST API if the format of it when registered is nested?
  95. How trigger to save post when updating post meta
  96. Create a Metabox that behaves Like a Taxonomy Box
  97. Views count with time limit per IP
  98. Generate an Email address from that of the Post Author
  99. Query 2 meta key values and a category
  100. trying to do if post meta !=0
Categories post-meta Tags post-meta
Function to Load Admin CSS for Super Admin on Multisite
Display WooCommerce product category on shop page (on every product)

Recommended Hostings

Cloudways: Realize Your Website's Potential With Flexible & Affordable Hosting. 24/7/365 Support, Managed Security, Automated Backups, and 24/7 Real-time Monitoring.

FastComet: Fast SSD Hosting, Free Migration, Hack-Free Security, 24/7 Super Fast Support, 45 Day Money Back Guarantee.

Recent Added Topics

  • Bug in translation system: load_theme_textdomain() returns true, files are available and accessible but the language defaults to english
  • Custom Elementor controls not appearing in the widget Advanced tab using injection hooks
  • Get the name of the template/*html file used
  • Trying to Add Paging to Single Post Page
  • Sharing media files between live and staging servers
  • How to display the description of a custom post type in the dashboard?
  • Critical error on image display
  • Copying WP data and files into new install?
  • How to determine the DirectAdmin WordPress backup date?
  • How to get list of ALL tables in the database?
© 2026 Read For Learn
  • Database
    • Oracle
    • SQL
  • algorithm
  • asp.net
  • assembly
  • binary
  • c#
  • Git
  • hex
  • HTML
  • iOS
  • language angnostic
  • math
  • matlab
  • Tips & Trick
  • Tools
  • windows
  • C
  • C++
  • Java
  • javascript
  • Python
  • R
  • Java Script
  • jQuery
  • PHP
  • WordPress