I'm using Advanced Custom Fields and I have Custom Post Type called 'recipe'.
I'm using this below code to set the custom post title, based on a custom field called recipe_name:
function my_post_title_updater( $post_id ) {
$my_post = array();
$my_post['ID'] = $post_id;
$recipe_name = get_field('recipe_name');
if ( get_post_type() == 'recipe' ) {
$my_post['post_title'] = get_field('recipe_name');
}
// Update the post into the database
wp_update_post( $my_post );
}
// run after ACF saves the $_POST['fields'] data
add_action('acf/save_post', 'my_post_title_updater', 20);
This above code works great.. but I'm trying to also figure out how to run the below function in addition, but I'm not seeing my post slugs get updated at all. They are saving as "auto-draft-4" and is incrementing up from there.
function slug_save_post_callback( $post_ID, $post, $update ) {
// allow 'publish', 'draft', 'future'
if ($post->post_type != 'recipe' || $post->post_status == 'auto-draft')
return;
// only change slug when the post is created (both dates are equal)
if ($post->post_date_gmt != $post->post_modified_gmt)
return;
// use title, since $post->post_name might have unique numbers added
$new_slug = sanitize_title( $post->post_title, $post_ID );
$subtitle = sanitize_title( get_field( 'subtitle', $post_ID ), '' );
if (empty( $subtitle ) || strpos( $new_slug, $subtitle ) !== false)
return; // No subtitle or already in slug
$new_slug .= '-' . $subtitle;
if ($new_slug == $post->post_name)
return; // already set
// unhook this function to prevent infinite looping
remove_action( 'acf/save_post', 'slug_save_post_callback', 21, 3 );
// update the post slug (WP handles unique post slug)
wp_update_post( array(
'ID' => $post_ID,
'post_name' => $new_slug
));
// re-hook this function
add_action( 'acf/save_post', 'slug_save_post_callback', 21, 3 );
}
add_action( 'acf/save_post', 'slug_save_post_callback', 21, 3 );