Home › Forums › Backend Issues (wp-admin) › Set WordPress excerpt and post thumbnail based on custom field › Reply To: Set WordPress excerpt and post thumbnail based on custom field
Try with the following code (make sure to either remove or rename the above/previous featured image function). Just replace your gallery field with get_field(‘thisisyourgalleryfield’, $post_id ) and see if it works.
add_action('acf/save_post', 'flex_FeaturedImageSetByACF', 50);
function flex_FeaturedImageSetByACF() {
$current_screen = get_current_screen(); // Current admin screen needed to identify the current cpt
$current_cpt_name = $current_screen->post_type; // Current cpt name
$current_cpt_support = 'thumbnail'; // We want to check if the CPT supports this feature
global $post;
$post_id = ( $post->ID ); // Current post ID
$post_gallery_field = get_field('thisisyourgalleryfield', $post_id ); // ACF field
if ( !empty( $post_id ) ) {
if ( isset( $post_gallery_field['0'] ) ) {
$post_image_id = $post_gallery_field['0']['id']; // ACF image filed ID
$post_image_url = $post_gallery_field['0']['url']; // ACF image filed URL
// If current cpt supports thumbnails/featured images
if ( post_type_supports( $current_cpt_name, $current_cpt_support ) ) {
if ( ( $post_image_url ) AND ( ( $post_image_url ) != ( get_the_post_thumbnail() ) ) ) {
update_post_meta($post_id, '_thumbnail_id', $post_image_id);
}
}
} else {
update_post_meta( $post_id, '_thumbnail_id', 0 );
}
}
}
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.