Support

Account

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

Solving

Automatic add uploaded images into acf gallery field

  • Hello. Guys, I need help.
    I have a website. And want to import posts with images. All images will be just “uploaded to the post media”. I need “show all attached images” into the gallery field by default.
    I found this thread: https://support.advancedcustomfields.com/forums/topic/acf_form-attachment-to-media-gallery/ And looks like I need a reverse solution.

    problem

    Sorry for my bad English. And thanks for help.

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

  • Thanks a lot.
    “field_5e31eaa74a594” – this is “Field Name” https://dl.dropboxusercontent.com/s/byf60bhltbf2x26/vpAiyAu3RQ.png correct?

  • that’s the field name, but for doing this you need to use the field key. On the field group edit screen click on screen option in the upper right an check the box for showing field keys.

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

The topic ‘Automatic add uploaded images into acf gallery field’ is closed to new replies.