Hi,
I would like to update the title of my post (with some data taken from custom fields) after insertion and with each update. Using save_post the whole thing works with updates but on the first insert the custom fields always come up empty even though they are valorized (if I then do an update without any changes it works). How can I do this?
Regards
Hello,
Please follow WP document to setup your custom PHP codes:
https://developer.wordpress.org/reference/hooks/save_post/
And I suggest you use a higher value for the "Priority" parameter, so it can be triggered after all other fields are saved into database, for example:
add_action( 'save_post', 'MY-CUSTOM-FUNCTION', 999 );
More help:
https://developer.wordpress.org/plugins/hooks/actions/#priority
Hi Luo Yang,
thank you. Even setting as priority 999 the custom fields are not displayed.
To get the custom field I run this command
$date = types_render_field( 'date' , array( 'post_id' => $post_id ));
In the update it works but in the first save it does not.
Regards
I have tried it in a fresh WP installation + the latest version of Toolset plugins, it works fine after you publish the post and refresh the browser, see below test site:
1) Login URL:
hidden link
2) Custom codes:
hidden link
Line 70~81:
add_action('save_post', 'my_function', 999, 3);
function my_function($post_ID, $post, $update){
remove_action('save_post', 'my_function', 999);
$date = types_render_field( 'date' , array( 'post_id' => $post_ID ));
$my_post = array(
'ID' => $post_ID,
'post_title' => 'Post title - ' . $date,
);
wp_update_post( $my_post );
add_action( 'save_post', 'my_function', 999, 3 );
}
3) Create a post, setup the date field value, publish and refresh your browser, I can see it works fine.
My issue is resolved now. Thank you!