First of: Your custom title suffix getting duplicated might not be what you want to happen, but is expected behavior as per your code sample.
The save_post
action hook runs everytime a post (or page) is created or updated. Hence your callback runs everytime.
Let me offer two solutions:
1 Use the wp_insert_post
action instead
The
wp_insert_post
action is called with the same parameters as the save_post action (the post ID for the post being created), but is only called for new posts and only aftersave_post
has run.
Note that, this hook does not have a posttype-specific equivalent, and hence you’d have to check for the type inside the callback function.
function modify_imac_title( $post_id ) {
if ( 'imac' === $_POST['post_type'] ) {
// do your thing
}
}
add_action( 'wp_insert_post', 'modify_imac_title' );
2. Add a boolean post_meta
Add a boolean post_meta that signifies, whether the title modification has run already.
function modify_imac_title( $post_id ) {
$title_modified = get_post_meta( $post_id, 'title_modified', true );
if ( ! $title_modified ) {
update_post_meta( $post_id, 'title_modified', true );
// do your thing
}
}
add_action( 'save_post_imac', 'modify_imac_title' );