Skip to content

Instantly share code, notes, and snippets.

@jimi008
Forked from LukaHarambasic/functions.php
Created March 31, 2018 01:51
Show Gist options
  • Save jimi008/b00a335a38d606da0b7ef5cd87f52dd6 to your computer and use it in GitHub Desktop.
Save jimi008/b00a335a38d606da0b7ef5cd87f52dd6 to your computer and use it in GitHub Desktop.
Wordpress: ACF-Field as CPT Title
// inspired by: https://gist.github.com/rveitch/9018669face1686e74aaa68026856f36
// add iitle to CPTs which doesn'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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment