Here's a solution that uses a static variable to prevent an infinite loop. This allows you to safely call wp_update_post()
inside of a function that is hooked to save_post
.
function km_set_title_on_save( $post_id ) {
// Set this variable to false initially.
static $updated = false;
// If title has already been set once, bail.
if ( $updated ) {
return;
}
// Since we're updating this post's title, set this
// variable to true to ensure it doesn't happen again.
$updated = true;
$date = get_post_meta( $post_id, 'rating_date', true );
$date_formatted = date( 'l, d.m.Y', strtotime( $date ) );
// Update the post's title.
wp_update_post( [
'ID' => $post_id,
'post_title' => 'TV ratings for ' . $date_formatted,
] );
}
add_action( 'save_post', 'km_set_title_on_save' );
Note: To limit this functionality to a certain post type, use the save_post_{$post->post_type}
hook instead of save_post.
register_post_type()
call.