Hook 'acf/save_post'
after ACF saves the $_POST['acf']
data. Then check to see if the post has_post_thumbnail
and set_post_thumbnail
if it doesn't.
function save_acf_image_to_post_thumbnail( $post_id ) {
$image = get_field( 'fl_image' );
if ( ! empty ( $image ) ) {
if ( ! has_post_thumbnail( $post_id ) ) {
$image_id = isset( $image[ 'id' ] ) ? $image[ 'id' ] : ( isset( $image[ 'ID' ] ) ? $image[ 'ID' ] : '' );
if ( ! empty ( $image_id ) ) {
set_post_thumbnail( $post_id, $image_id );
}
}
}
}
add_action( 'acf/save_post', 'save_acf_image_to_post_thumbnail', 20 );
This assumes the Return Value
is an Image Object
.
It's also possible to trick has_post_thumbnail
and post_thumbnail_html
to render your custom field Image URL
when the metadata is missing.
Spoof has_post_thumbnail
:
function filter_post_metadata( $value, $object_id, $meta_key, $single ) {
if ( $meta_key === '_thumbnail_id' && ! $value ) {
return empty ( get_field( 'fl_image' ) ) ? $value : - 1;
}
return $value;
}
add_filter( 'get_post_metadata', 'filter_post_metadata', 20, 4 );
Doctor post_thumbnail_html
:
function filter_post_thumbnail_html( $html, $post_ID, $post_thumbnail_id, $size, $attr ) {
$image = get_field( 'fl_image' );
if ( ! empty( $image ) && (empty( $post_thumbnail_id ) || $post_thumbnail_id === -1) ) :
$html = sprintf( '<img width="%s" height="auto" src="%s" class="attachment-post-thumbnail size-post-thumbnail wp-post-image" >', "100%", esc_url( $image) );
endif;
return $html;
}
add_filter( 'post_thumbnail_html', 'filter_post_thumbnail_html', 20, 5 );
_thumbnail_id
and the value is an attachment ID, so you would need to save your image properly as an attachment for things to work out. There's an easy way out, possibly, if you control your theme and can edit the code. You could check for a featured image and if there isn't one, display your image instead. If that's an acceptable alternative, let me know and I'll knock up some code.print_r($image)
to your code?