Support

Account

Home Forums ACF PRO Using ACF URL field as Featured Image

Solved

Using ACF URL field as Featured Image

  • Hello,

    Just starting out with ACF with very limited PHP knowledge. Does anyone by any chance know of a code snippet that can be used for a CPT where an ACF URL field (lets call it new_fi) is referenced as the Featured Image.

    Many thanks

  • It is not possible to use a URL field directly as a featured image.

    What you would have to do is a bit complicated and I am not sure that there are any examples available.

    You would need to create an acf/save_post action priority > 10 to run after ACF has saved field values.

    In this filter you would need to use media_sideload_image() to import the image to WP.

    The you would use the imported attachment ID returned by that function to set the image as the featured image for the page using set_post_thumbnail().

    here is a basic filter

    
    add_action('acf/save_post', 'featured_image_from_url, 20);
    featured_image_from_url($post_id) {
      $url = get_field('image_url_field_name', $post_id);
      if (empty($url)) {
        return;
      }
      $attachment_id = media_sideload_image($url, $post_id, NULL, 'id');
      if (is_wp_error($attachment_id)) {
        // error importing image
        // you might want to figure out how to report the error
        return;
      }
      set_post_thumbnail($post_id, $attachment_id);
    }
    

    Alternately you might consider using an acf/validate_value filter instead of an acf/save_post action. In the validate value filter you could do basically the same thing and it would allow you to show an error on the page if the image cannot be imported.

  • Many thanks John,

    I think you’ve put me on the right path !

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.