Loading custom values into ACF field default values

A plugin I’m working on requires that the user be able to set the map center for a Google Map ACF field that is associated with a custom post type. Advanced Custom Fields has a good number of filters, but I wasn’t sure going in which filter I needed to use.  A quick Google lead me to this question on the ACF support forums which in turn led to this page on the ACF documentation.  From there it was as simple as plugging in my field names and values.

In the ACF JSON file for the options page, here is the field that allows the user to set the default map center:


{
"height": "",
"center_lat": "38.641265",
"center_lng": "-90.2881593",
"zoom": "",
"key": "field_5858518f3db94",
"label": "Map Center",
"name": "washu_ppi_places_map_center",
"type": "google_map",
"instructions": "",
"required": 0,
"conditional_logic": [
[
{
"field": "field_585839fb5f5d8",
"operator": "==",
"value": "places"
}
]
],
"wrapper": {
"width": "",
"class": "",
"id": ""
}
}

Here is the JSON for the map field on the CPT:


{
"height": "",
"center_lat": "38.641265",
"center_lng": "-90.2881593",
"zoom": "",
"key": "field_58545be03c13a",
"label": "Location\/Map",
"name": "washu_ppi_map",
"type": "google_map",
"instructions": "",
"required": 0,
"conditional_logic": 0,
"wrapper": {
"width": "",
"class": "",
"id": ""
}

And finally here is the code to put in the plugin constructor:


add_filter( 'acf/load_field/name=washu_ppi_map', array( self::$instance, 'set_default_google_maps_center' ) );
public static function set_default_google_maps_center( $field ) {
$google_map_center = get_field( 'washu_ppi_places_map_center', 'option' );
$field[ 'center_lat' ] = $google_map_center[ 'lat' ];
$field[ 'center_lng' ] = $google_map_center[ 'lng' ];
return $field;
}

There are a few different filters you can hook onto depending on if you know the field key or if you want to set the values for all Google maps, but I chose to use this way since the field name is what we have the most control over.


Posted

in

,

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.