Useful Snippets

Welcome!


This blog is used to collect useful snippets related to Linux, PHP, MySQL and more. Feel free to post comments with improvements or questions!

Are your smart devices spying on you? Make better purchasing choices and find products that respect your privacy at Unwanted.cloud

RSS Latest posts from my personal blog


Subscribe to RSS feed


Dynamically populating Advanced Custom Fields values

Stanislav KhromovStanislav Khromov

Populating fields dynamically in ACF is simple using the acf/load_field hook. An example:

//Populate the Select field field_5587fccf24f38 with dynamic values
add_filter('acf/load_field/key=field_5587fccf24f38', function($field) {
  //These can be dynamically generated using any PHP code
  $field['choices']['one'] = 'Choice one';
  $field['choices']['two'] = 'Choice two';

  return $field;
});

But if you also use ACF Local JSON, you’ll notice that your dynamic field values get exported whenever you re-resave one of your field groups. Not ideal.

Using dynamic values with ACF Local JSON

We need a way to remove the dynamic values just before they are exported to Local JSON. Luckily, there’s an undocumented filter called acf/prepare_field_for_export that will let us do this! Example:

//Don't export dynamic values via Local JSON
add_filter('acf/prepare_field_for_export', function($field) {

  //If we're at the correct field
  if(isset($field['key']) && $field['key'] === 'field_5587fccf24f38') {

    //Blank out the select options with an empty array
    $field['choices'] = array();
  }

  return $field;
});

Updated 2016-01-15
There was another filter called acf/prepare_fields_for_export (note fields instead of field). This filter was removed in ACF 5.3.3.

Full-stack impostor syndrome sufferer & Software Engineer at Schibsted Media Group

Comments 1
  • clynesr
    Posted on

    clynesr clynesr

    Reply Author

    Hi,
    I’m searching everywhere but still can find. And now i read ur article and decide to ask.
    My author can update their user fields on frontend with acf_form. Such as user fields on profile region,state and city. Also my author can publish posts (wp posts or cpt) on frontend via form. Also, this posts using region,state and city taxonomies.
    1 – When author want to create and publish new post, taxonomies value will get from user fields. If, in the future, author update any user field such as changed region than author’s all posts taxonomy value region will update automatically. If this possible, how does effect wordpress database performance (also think lots of authors)

    2 – Post taxonomies also can load and save from acf field. So, on create new post page, acf post field group fileds value (region, state and city) can load from user field, if author can update value for only that post. So, in the fute, author change user field, dont effects other posts taxonomy values.

    Thanks
    Regards