A post’s title (post_title
) is not saved in meta data; it’s a field within the post table.
Here’s an updated version of your original code.
-
Infinite loop is
prevented
by removing and then readding thewpse246957_update_post_info
callback. -
Post title is successfully saved with the suffix
- $post_id
A
check is in place to
prevent the suffix from being re-added if it has already been added.
add_action( 'save_post', 'wpse246957_update_post_info', 10, 3 );
function wpse246957_update_post_info( $post_id, $post, $update ) {
// Stop anything from happening if revision
if ( wp_is_post_revision( $post_id ) ) {
return;
}
// unhook this function so it doesn't loop infinitely
remove_action( 'save_post', 'wpse246957_update_post_info' );
// get post type
$post_type = get_post_type( $post_id );
// If this isn't a custom post, don't update it.
// if ( "cbre_access_form" != $post_type ) return;
// run codes based on post status
$post_status = get_post_status();
if ( $post_status != 'draft' ) {
if ( isset( $_POST['post_title'] ) ) {
$suffix = ' - ' . $post_id;
if ( ! preg_match( "https://wordpress.stackexchange.com/" . preg_quote( $suffix, "https://wordpress.stackexchange.com/" ) . '$/', $_POST['post_title'] ) ) {
wp_update_post( [
"ID" => $post_id,
"post_title" => $_POST['post_title'] . $suffix,
] );
}
}
}
// re-hook this function
add_action( 'save_post', 'wpse246957_update_post_info', 10, 3 );
}
Personally, I’d probably append the suffix before outputting the title in your template file or wherever you are outputting the title because there could be some edge case with the approach above when it comes to re-saving the post title.