Support

Account

Home Forums Front-end Issues featured image from relationship field (backend) Reply To: featured image from relationship field (backend)

  • If you can select multiple then ACF is returning an array. My code actually eliminates the return value so that doesn’t matter (forgot that), but we do have to deal with the possibility of an array return value. This will only work to get the first related post selected

    
    add_action('acf/save_post', 'copy_image_from_relationship', 20);
    function copy_image_from_relationship($post_id) {
      // check the post type
      if (get_post_type($post_id) != 'print-size') {
        // not the right post type
        return;
      }
      // get the post id for the related post
      $related_id = get_field('relationship_field_name', $post_id, false);
      if (is_array($related_id) && !empty($related_id)) {
        $related_id = $related_id[0];
      }
      if (!empty($related_id)) {
        // get the featured image ID from the related post
        $image_id = get_post_thumbnail_id($related_id);
        if ($image_id) {
          // set on current post being updated
          update_post_meta($post_id, '_thumbnail_id', $image_id);
        }
      }
    }