I was also concerned about this issue. Here is an example of code that sets the thumbnail of the standard image field:
<?php
function acf_set_featured_image( $value, $post_id, $field ){
if($value != ''){
//Add the value which is the image ID to the _thumbnail_id meta data for the current post
add_post_meta($post_id, '_thumbnail_id', $value);
}
return $value;
}
// acf/update_value/name={$field_name} - filter for a specific field based on it's name
add_filter('acf/update_value/name=cursusfoto', 'acf_set_featured_image', 10, 3);
?>
However, this code does not work with this plugin. What can be wrong?
Here in this forum of support ACF discusses this issue:
Set image as featured image – ACF Image Crop Add-on
I hope the author of the plugin will pay attention to this topic.
Hi there,
This does not work due to the way this plugin stores data. It stores both the original and the cropped image id as a json string, so to make it work with the above you need to perform an extra check.
The following should work both for regular image fields and image crop fields:
<?php
function acf_set_featured_image( $value, $post_id, $field ){
$id = $value;
if( $id && ! is_numeric( $id ) ){
$data = json_decode( stripcslashes($id), true );
$id = $data['cropped_image'];
}
if( $id ){
add_post_meta( $post_id, '_thumbnail_id', $value );
}
return $value;
}
// acf/update_value/name={$field_name} - filter for a specific field based on it's name
add_filter( 'acf/update_value/name=featured_image_test', 'acf_set_featured_image', 10, 3 );
?>
Let me know how it works out.
Best,
Anders
Anders, unfortunately, I was not able to achieve success with your code. What could I do wrong? Which fields you need to specify:
['cropped_image']
name={$field_name}
acf/update_value/name=featured_image_test ?
I use a single image crop field “post-image”, which returns the ID of the image. The form is located in the frontend mode.
You should change featured_image_test with your field name (post-image?).
No, unfortunately, is not working.
I’m sorry. The code below should work.
Please note that unlike the your original snippet, this will also remove the featured image if the image is removed.
<?php
function acf_set_featured_image( $value, $post_id, $field ){
$id = $value;
if( ! is_numeric( $id ) ){
$data = json_decode( stripcslashes($id), true );
$id = $data['cropped_image'];
}
update_post_meta( $post_id, '_thumbnail_id', $id );
return $value;
}
?>
Excellent! It works! Please accept my gratitude.