The filter title_save_pre
runs before the post is written to the database, and also before any of its post meta is saved to the database. So get_post_meta
at this point will be blank for the first run, and always return ‘old’ data.
To correct this you’ll want to hook into save_post
and update the post from there. save_post
runs after the post has been saved to the database, and the in-built ‘custom fields’ have been saved.
To do this you can use wp_update_post
. However, you’ll need to be careful:
When executed by an action hooked into save_post (e.g. a custom metabox), wp_update_post() has the potential to create an infinite loop. This happens because (1) wp_update_post() results in save_post being fired and (2) save_post is called twice when revisions are enabled (first when creating the revision, then when updating the original post—resulting in the creation of endless revisions).
If you must update a post from code called by save_post, make sure to verify the post_type is not set to ‘revision’ and that the $post object does indeed need to be updated.
One way round this is to remove the save_post
callback from the hook inside the callback, as demonstrated here.