My assumptions and assessment of the behaviour appear to be correct. By using a transition hook drat_to_publish
or pending_to_publish
for example, you’re actually pausing the publish process. Any changes you make to the post are irrelevant, regardless of the method used to update the post, because once the code returns from your custom function, the publishing process continues with the data already held in cache and so any changes you made are lost. By changing the hook to publish_my_post_type
(where my_post_type is the $post->post_type
of my custome posts) the function called is running after the publishing process. But importantly the hook has the post ID, so you can use that to do what ever you like to the meta data. Here is my updated code:
add_action('publish_my_post_type', array($this, 'set_expiry_date'));
public function set_expiry_date($postID) {
$post = get_post($postID);
$new_value="2025-06-20"; //this is for example and would normally be generated dynamically
update_post_meta($post->ID, '_expiry_date', $new_value );
}
Unlike any of my previous attempts, this works every time, and I’m able to use the preferred WordPress function. Getting the $post
object is not entirely necessary in this sample code, but in my full code I’m doing other things so I’ve left it in just as an example and aid to others.