Home › Forums › General Issues › Using first gallery image as the featured image…
I am using the following code to make it so that the first image in the gallery field is selected as the featured image for that post:
//make first gallery image featured image
add_filter('acf/save_post', 'gallery_to_thumbnail');
function gallery_to_thumbnail($post_id) {
$gallery = get_field('gallery', $post_id, false);
if (!empty($gallery)) {
$image_id = $gallery[0];
set_post_thumbnail($post_id, $image_id);
}
}
This works when I publish in admin, but when a user creates a new post on the front end, the featured image is not set.
Using PHP will only work when you click the update button and will not assign the image to the featured image when you do so. I would call this working as expected.
If you want to have the first gallery image automatically populate in the featured image before updating the post then you’ll need to build custom JavaScript to do this. https://www.advancedcustomfields.com/resources/adding-custom-javascript-fields/
Thanks for your reply John.
I managed to make this work with the following code:
add_filter('acf/save_post', 'gallery_to_thumbnail',11,11);
function gallery_to_thumbnail($post_id) {
$gallery = get_field('images', $post_id, false);
var_dump($gallery);
var_dump($post_id);
if (!empty($gallery)) {
$image_id = $gallery[0];
set_post_thumbnail($post_id, $image_id);
}
I realised my issue isn’t with setting the featured image but setting the og:image based on the featured image for which I am using Yoast plugin. This only works once I update a post rather than create one.
I know Yoast has a filter but I am unsure how to set it using the gallery field, any ideas would be greatly appreciated:
add_filter('wpseo_opengraph_image', 'og_image');
function og_image($image) {
global $post;
if (get_field('feature_image', $post->ID)) {
$image = base_image_url(get_field('feature_image', $post->ID), null);
}
return $image;
}
not sure but maybe this will help https://github.com/Yoast/wordpress-seo/issues/1060
The topic ‘Using first gallery image as the featured image…’ is closed to new replies.
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.