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...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.