I've been trying to achieve this for a bit now, and having no success. I have a custom post type "Contributor" where I've disabled the default title field, and I'm trying to figure out how to set a custom title based on four values from Advanced Custom Fields:
- a "Corporate?" checkbox;
- a Corporate Name text field (if Corporate is checked);
- a combination of Given Names and Surnames text fields (if Corporate is unchecked).
I'm using this function to put together the full name for the Admin columns, for example:
function biwp_contributor_name($post_id) {
$corporate = get_field('biwp_corporate', $post_id ); //get Corporate checkbox value
if ($corporate) { //if Corporate is checked, use biwp_cname (Corportate Name)
$name = get_field('biwp_cname', $post_id );
} else { //if Corporate is unchecked, use biwp_gnames (Given Names) and biwp_snames (Surnames)
$gnames = get_field('biwp_gnames', $post_id );
$snames = get_field('biwp_snames', $post_id );
$name = $gnames .' '. $snames;
}
return $name;
}
And that works great for display purposes. But the problem is that a lot of things in WP rely on the default title, so it would be much better to use that function to actually create the post title (and slug) instead.
I've seen a few other threads on this topic, tried a few different solutions, but to no avail. This one is derived from posts in this ACF forum thread:
add_filter('acf/update_value', 'biwp_fix_contributor_title', 10, 3);
function biwp_fix_contributor_title( $value, $post_id, $field ) {
if (get_post_type($post_id) == 'contributor') {
$name = biwp_contributor_name($post_id);
$new_title = $name;
$new_slug = sanitize_title( $new_title );
// update post
$biwp_contributor = array(
'ID' => $post_id,
'post_title' => $new_title,
'post_name' => $new_slug,
);
if ( ! wp_is_post_revision( $post_id ) ){
// unhook this function so it doesn't loop infinitely
remove_action('save_post', 'biwp_fix_contributor_title');
// update the post, which calls save_post again
wp_update_post( $biwp_contributor );
// re-hook this function
add_action('save_post', 'biwp_fix_contributor_title');
}
}
return $value;
}
And this one is from this SE thread:
add_action('save_post', 'biwp_fix_contributor_title', 12);
function biwp_fix_contributor_title ($post_id) {
if ( $post_id == null || empty($_POST) )
return;
if ( !isset( $_POST['post_type'] ) || $_POST['post_type']!='contributor' )
return;
if ( wp_is_post_revision( $post_id ) )
$post_id = wp_is_post_revision( $post_id );
global $post;
if ( empty( $post ) )
$post = get_post($post_id);
if ($_POST['biwp_corporate']!='') {
global $wpdb;
$name = biwp_contributor_name($post_id);
$where = array( 'ID' => $post_id );
$wpdb->update( $wpdb->posts, array( 'post_title' => $name ), $where );
}
}
But neither seems to actually do anything—not even a negative, undesired effect—which really makes me wonder.
Thanks in advance for any help.