Support

Account

Home Forums Add-ons Gallery Field Automatic add uploaded images into acf gallery field Reply To: Automatic add uploaded images into acf gallery field

  • You need to use an acf/load_value filter and you need to use the field key

    
    add_filter('acf/load_value/key=field_5e31eaa74a594', 'pop_gal_w_attach', 20, 3);
    function pop_gal_w_attach($value, $post_id, $field) {
      if (!empty($value)) {
        // gallery has images in it, don't repopulate
        return;
      }
      // get images attached to this post
      $media = get_attachment_media('image', $post_id);
      if ($medias) {
        // populate value with attachments IDs
        $value = array();
        foreach ($media as $post) {
          // acf stores the IDs internally as strings
          $value[] = strval($post->ID);
        }
      }
      return $value;
    }
    

    When you want to get the field on the front end you must also use the field key. If you use the field name and it has never been updated then ACF will not call your filter.

    
    $gallery = get_field('field_5e31eaa74a594');
    

    Also, you should be aware that if someone deletes all the images in an image gallery and saves the post with no images that the gallery field will be repopulated with all of its attachments again. There isn’t a way to detect if a gallery is empty because it was never updated with a value or because the post was saved with no value.