这里有一个使用静态变量来防止无限循环的解决方案。这允许您安全地呼叫wp_update_post()
连接到的函数的内部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\' );
注意:要将此功能限制为特定的帖子类型,请使用
save_post_{$post->post_type}钩住而不是save\\u post。