Skip to content

Instantly share code, notes, and snippets.

@LukaHarambasic
Last active August 8, 2021 10:32
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save LukaHarambasic/e908303e25e7a49049d73abc9991db6e to your computer and use it in GitHub Desktop.
Save LukaHarambasic/e908303e25e7a49049d73abc9991db6e to your computer and use it in GitHub Desktop.
Wordpress: ACF-Field as CPT Title
// inspired by: https://gist.github.com/rveitch/9018669face1686e74aaa68026856f36
// add title to CPTs which don't provide a title (useful for the relationship field (https://www.advancedcustomfields.com/resources/relationship/))
function sync_acf_post_title($post_id, $post, $update) {
$post_type = get_post_type($post_id);
// check for the current CPT
if($post_type === "cpt_name_1") {
// get the field you want to save in the title
$title = get_field('acf_field_name', $post_id);
} else if($post_type === "cpt_name_2") {
$title = get_field('acf_field_name', $post_id);
} else {
//if it's not a CPT, the title should be saved as usual
$title = $post->post_title;
}
$content = array(
'ID' => $post_id,
'post_title' => $title
);
// to prevent a loop
remove_action('save_post', 'sync_acf_post_title');
wp_update_post($content);
}
// is triggered when a user presses the update or publish button
add_action('save_post', 'sync_acf_post_title', 10, 3);
@xdkore
Copy link

xdkore commented Jan 7, 2018

Thanks for this, how do you add more than one field? i have four mandatory fields i want to make the title. also is it possible to add a taxonomy field? i and very new at all this. thanks for any feed back.

$title = get_field('acf_field_name', $post_id);
$title = get_field('acf_field_name2', $post_id);

@saya972
Copy link

saya972 commented Aug 6, 2021

Excellent, thank you very much !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment