Support

Account

Home Forums Backend Issues (wp-admin) ACF load_value to Gallery Field Reply To: ACF load_value to Gallery Field

  • Hi John,

    Many thanks for the response!

    What I’m trying to do is take the array of images from a posts slider Id so that I can populate the gallery field and eventually remove the royalslider plugin as a dependency. There are hundreds of posts so I didn’t want to have to create each gallery from scratch.

    Here’s an example of how the royalslider plugin stores an array in its ‘slides’ column in the database:

    
    [{"title":"Slider 47","image":{"attachment_id":"1653"}},{"title":"Image-1","image":{"attachment_id":"1652"}},{"title":"Image-2","image":{"attachment_id":"1651"}},{"title":"Image-3","image":{"attachment_id":"1650"}},{"title":"Image-4","image":{"attachment_id":"1649"}},{"title":"Image-5","image":{"attachment_id":"1648"}}]
    

    Using your ammendments I can now link to the correct slider ID but images are not being loaded into the gallery field:

    
    add_filter('acf/load_value/key=field_5e2058d65e519', 'build_gallery_from_rs', 10, 3);
    
    function build_gallery_from_rs($value, $post_id, $field) {
      if (!empty($value)) {
        // already has a value
        return $value;
      }
      // does not have a value, build value from slider attachments
      global $wpdb;
      $table = $wpdb->prefix . 'new_royalsliders';
      $id = get_field('media_gallery_slider', $post_id, false);
      $slider_data = $wpdb->get_results( $wpdb->prepare("SELECT * FROM $table WHERE id=%d", $id), ARRAY_A );
      // How to build image array?
      $media = $slider_data[0];
      $value = array();
      if ($media) {
        foreach ($media as $image) {
          $value[] = $image->ID;
        }
      }
      return $value;
    }