Set post title and slug upon initial post creation (using Types for custom post type and fields)
<?php
// This snippet: https://gist.github.com/cliffordp/c5fc837ba07a8037d040
// Adapted from https://wp-types.com/forums/topic/how-to-set-post-title-upon-initial-post-creation/#post-307205
// Another implementation to take into consideration: https://github.com/moderntribe/tribe-common/blob/4.12.12/src/Tribe/Tracker.php#L292
add_action( 'post_updated', 'my_post_updated_func' );
function my_post_updated_func( $post_id ) {
// Only do for this post type. Change for your CPT
$post_type = 'my-cpt';
// Types custom field (gets prefixed with "wpcf-") that's used to set post title and slug
$field_slug = "my-field";
// If this is just a revision, don't
if ( wp_is_post_revision( $post_id ) || get_post_type( $post_id ) != $post_type ) {
return;
}
remove_action( 'post_updated', 'my_post_updated_func' );
$title_and_slug = get_post_meta( $post_id, "wpcf-$field_slug", true );
if ( isset ( $_POST['wpcf'][$field_slug] ) && ! empty ( $_POST['wpcf'][$field_slug] ) ) {
$title_and_slug = $_POST['wpcf'][$field_slug];
}
$my_args = array(
'ID' => $post_id,
'post_title' => $title_and_slug,
'post_name' => sanitize_title( $title_and_slug ),
);
// update the post, which calls save_post again
$res = wp_update_post( $my_args, true );
add_action( 'post_updated', 'my_post_updated_func' );
}