Home Forums Add-ons Gallery Field Problem with use acf/format_value/ filter for gallery field


Problem with use acf/format_value/ filter for gallery field

  • Hello,

    I’m trying to add more fields to array returned by gallery field, basically I have some custom meta for attachments, and I want to populate them to ACFs gallery return array.

    I was trying to use acf/format_value/type=gallery filter, but no matter what I was doing there, there was either no result at all, or I was getting empty array.

    While trying to debug a code, it looks like $value is an array, but when I was trying to get into single image in foreach, it looks like each element is string, not an array with names, sizes, etc.

    Was trying to google it, there and didn’t find anything working or useful here or stackoverflow. Would be glad if anyone could provide me some working pice of code as an example, I will figure out the rest from there.

  • Hope this helps you

    // add filter w/high priority so it runs after ACF
    add_filter('acf/format_value/name=gallery', 'add_values_to_gallery', 20, 3);
    function add_values_to_gallery($value, $post_id, $field) {
      if (!$value || !is_array($value) || !count($value)) {
        // no value, bail early
        return $value;
      // loop through gallery
      // note & before $images => pass by reference
      // so that changes to $image effect original
      foreach ($value as $index => &$image) {
        // add a value to this image
        $image['my-new-index'] = 'my new value';
      return $value;
  • Yes, that helps. Wondering what was the issue, priority? While I was trying withacf/format_valueand acf/load_value before the most what I got in dump was array of only attachments IDs from gallery, so I guess that it was the main reason for those filters to for example add more images to gallery by code, and then other hooks will generate arrays of their data later on?

    Do ACF have some more detailed documentation somewhere?

    Thank you 🙂

  • More than likely it was probably priority and your filter was running after ACF. Before ACF runs all you’ll get is an array of IDs so that makes sense. If you run it before ACF then you’d basically just want to add IDs, for example a default image in each gallery.

    The documentation on the site is the best you’ll find, for the most part. Unless you find a tutorials by other people. I’ve figured out most of what I know by trial and error and doing a lot of echo somethings and print_r(something).

    The main thing to remember when creating filters is that ACF uses the same hooks to do the work that are in the documentation for us to use and 99% of these happen at the default priority of 10. What you’ll see a <10 will be significantly different than what you’ll see at >10

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

The topic ‘Problem with use acf/format_value/ filter for gallery field’ is closed to new replies.