My front page template is set to display the full content of the latest post using WP_Query and a custom page template. Now I want the home page featured image to dynamically change every time a new post is published. The goal is to show the first image from the latest post’s ACF gallery when sharing the home page on social media.
I am not great with PHP so Im not sure if I am even approaching this the right way. So far this code does nothing. Do I need to hook my function to something else? Where am I going wrong?
// Set front page featured image to first image in surf report cpt ACF gallery
function set_home_featured_image_from_ACF_gallery () {
global $post;
// Get front page id
$frontpage_id = get_option( 'page_on_front' );
// Get id of latest post
$recent_posts = wp_get_recent_posts( array( 'numberposts' => '1' ) );
// Set $post_id variable to latest post id
$post_id = $recent_posts[0]['ID'];
if ( is_front_page() ) {
/* Get the home page thumbnail (should i be getting the home page thumbnail here or the post thumbnail of the latest post?) */
$has_thumbnail = get_the_post_thumbnail($frontpage_id);
// Get the first image from the ACF gallery in the latest post
$images = get_field('surf_report_gallery', $post_id, false);
$image_id = $images[0];
if ( $image_id ) {
// Set home page featured image to first ACF image
set_post_thumbnail( $frontpage_id, $image_id );
}
}
}
add_action( 'save_post', 'set_home_featured_image_from_ACF_gallery' );
Also, every time I share the home page it wants to display an image that I have removed from the site completely. Even when I manually add a featured image in the page editor. Weird…
When working with ACF it is almost always best to use use acf/save_post https://www.advancedcustomfields.com/resources/acf-save_post/. There is no guarantee that ACF will have saved values using WP save_post hook.
add_action('acf/save_post', 'set_home_featured_image_from_ACF_gallery');
function set_home_featured_image_from_ACF_gallery($post_id) {
// still need to do this
$recent_posts = wp_get_recent_posts(array( 'numberposts' => '1'));
if ($post_id != $recent_posts[0]->ID) {
// this post is not the most recent post
return;
}
$frontpage_id = get_option('page_on_front');
$images = get_field('surf_report_gallery', $post_id, false);
$image_id = 0;
if (!empty($images)) {
$image_id = $images[0];
} else {
// backup, use the post featured image?
$image_id = get_post_thumbnail_id($post_id);
}
if ($image_id) {
// remove the if statement if you want to remove the feature image
// if a new image is not found
set_post_thumbnail($frontpage_id, $image_id);
}
}