Last active
August 8, 2021 10:32
-
-
Save LukaHarambasic/e908303e25e7a49049d73abc9991db6e to your computer and use it in GitHub Desktop.
Wordpress: ACF-Field as CPT Title
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Excellent, thank you very much !