extended-acf
extended-acf copied to clipboard
Add customFormat method to Field class
This is a feature idea/request that I figured would be easier to share via a PR. Here's the gist: I would like to make it easy to customize the response format of any given field via a customFormat field method (open to better name suggestions); this method would be available to ALL fields, and is therefore defined in the root Field class. It simply leverages ACF's acf/format_value/key={field_key} filter hook under-the-hood -- so you pass a callback function into customFormat in the same way you would pass it to that filter hook. When the get method runs for a field, it checks if a customFormat callback was provided, and sets up the filter for you using the auto-generated (or user-provided) field key.
Example:
Relationship::make('Related Project')
->postTypes(['project'])
->customFormat(function ($value, $post_id, $field) {
if (!is_array($value))
return $value;
return array_map(function ($project) {
return [
'id' => $project->ID,
'post_title' => $project->post_title,
'custom_field' => 'whatever'
];
}, $value);
})
This is particularly valuable for the types of projects I build, which are headless/decoupled sites where WP is essentially just a REST API that my JS frontends consume; I often need to tweak ACF field formats to expose stuff to the REST API that isn't included by default, or to remove unnecessary nested properties that bloat my API request payload sizes etc. (like my example above which trims out a bunch of bloat that Relationship fields often include). I have so far been using the acf/format_value filter hook to adjust field types globally (i.e. add_filter('acf/format_value/type=image' ...);), but I have recently come across the need to adjust formatting for specific/one-off fields; I can manually set up the filter hook for a given field if I manually provide a key to the field via the key method, but I would prefer to continue leveraging the auto-generated field keys and I find the customFormat method much cleaner in general.
Thoughts?