Hey! So I’m looking for a quick way to initialize option page fields when a theme first activated. The goal is to be able to access fields using get_option right out of the gate (so there needs to be a record of that field in the database)
I know that I can do this by writing a series of update_field commands but it seems like awfully redundant work, especially being that in a returned field object that the default value is automatically returned.
So I thought about using a filter to do this.
Somethings like
function add_default_acf_options ($value, $post_id, $field) {
if (!$value) {
update_field($field['key'], $field['default_value'], 'option');
}
return $value;
}
add_filter('acf/load_value', 'add_default_acf_options', 10, 3);
But I’m sure you can imagine this causes more problems than it actually solves. is there a way to accomplish initialization without having a manually code this in?
I have done this before, and it is usually when I’m working on building a plugin but could be applied to a theme as well.
What I do is export from ACF to code. I then add two functions in the class that I’m building and I separate the field group settings and the fields
A simple class might look like this:
new my_new_class();
class my_new_class {
public function __construct() {
add_filter('get_my_field_group_fields' array($this, 'get_my_field_group_fields'), 10, 1);
}
public function get_my_field_group_fields($fields) {
$fields = array(
// this is where all the fields used
// to create the field group go
);
return $fields;
}
}
Then to initialize my fields, in the function I create to activate the plugin I do:
$feilds = apply_filters('get_my_field_group_fields', array());
I then loop through the list of fields, get the field name, field key and the default value and in the loop create the options that need to be inserted.