I have a custom post type called “videos”, which also has a few custom fields defined. Upon creating or updating a “videos” post, I would like to run a function.
Unfortunately, this function needs the values of the post meta data for the post that I’ve just created, and the usual hooks (save_post
,publish_post
, etc.) seem to run before the post meta is inserted into the database, so it isn’t available.
If I manually update the post just by clicking “Publish” without making any changes, function works properly.
Is there a hook that fires later in the process, after all metadata has been inserted?
There is an
undocumentedhook calledupdated_post_meta
that does what I need.It will pass 4 parameters to the hooked function: the meta ID, the object ID (same as the post ID), the meta key, and the meta value. In my hooked function I check to see if the meta key name is the field that I need the value of and, if so, it proceeds.
Here’s what it looks like:
By the way, unlike
added_post_meta
, you do not replacepost
with the post type that you are targeting. In my case, the name of the post type isvideos
, but I still had to useupdated_post_meta
and NOTupdated_videos_meta
.The reason post meta is not available yet it is because they use save_post hook to save post meta. So, you hook is not running after post meta is saved to database.
Two solutions to your problem.
add_action(‘save_post’, ‘my_function’);
function my_function($post_id){
}
add_action(‘save_post’, ‘my_function’, 12 , 3);
function my_function($post_id, $post, $update){
}