Home › Forums › General Issues › Get_fields() returns false until I update the post › Reply To: Get_fields() returns false until I update the post
Ignore me! I fixed it! I read on the API page that when creating the post programatically, I need to use $field_key instead of $field_name as the first param of update_field().
I’ve written a little utility function for anyone else who wants to use the $field_name instead of $field_key when programatically adding a post and then a custom field value.
The $params argument is the array used when calling register_field_group(), $field_name is obviously the field name.
// Function to get an ACF Key for a field based on the params used to create the fieldset
function acf_field_key($params = array(), $field_name) {
if (empty($params) or !isset($params['fields'])) {
return $field_name;
}
// Loop and find the value
foreach ($params['fields'] as $field) {
if ($field['name'] == $field_name) {
return $field['key'];
}
}
}
Usage:
$field_key = acf_field_key($acf_init_args, $field_name);
update_field($field_key, $value, $post_id);
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.