Hello,
I’m trying to add the main ID of the post image to the ACF gallery database table, but I’m not getting it, because when I add it via update_field it adds correctly, but I lose the rest of the images of the gallery.
$post_thumb = get_post_thumbnail_id( get_the_ID() );
update_field( 'gallery', $post_thumb, get_the_ID() );
Can anybody help me please?
A gallery field stores an array of post ID’s. To add an image you first need to get the value and add the new ID value to it.
$gallery = get_field('gallery', get_the_ID(), false); // get unformatted value
if (empty($gallery)) {
$gallery = array();
}
$gallery[] = get_post_thumbnail_id(get_the_ID());
update_field('gallery', $gallery, get_the_ID());
This works perfectly @hube2, thank you so much!!!
I am very happy now, thanks!!!
Hello again @hube2,
Is there a way to make the post_thumbnail_id the first item in the gallery and not the last?
The code you posted works correctly, but the thumbnail is added as the last item in the gallery.
I would appreciate some help on this, please.
Works correctly, thanks again John Huebner!
Thanks works as expected!