Support

Account

Home Forums General Issues Dynamically set front page featured image from first image in latest post's ACF Reply To: Dynamically set front page featured image from first image in latest post's ACF

  • 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);
      }
    }