Skip to content

Instantly share code, notes, and snippets.

@dfinnema
Last active February 26, 2024 20:35
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dfinnema/da4c6afdff2eaa4274f3709585d80c8e to your computer and use it in GitHub Desktop.
Save dfinnema/da4c6afdff2eaa4274f3709585d80c8e to your computer and use it in GitHub Desktop.
Wordpress - ACF - Adds all the fields with default values to the Post Meta for Advanced Custom Fields
/**
* Sets the ACF Fields for the specified post
* @param int $post_id
* @param string $post_type
*/
function set_post_defaults_acf($post_id=0,$post_type='') {
if ($post_id &&
$post_type &&
function_exists('update_field')
) {
// Get field groups for this post type and id.
$field_groups = acf_get_field_groups(array(
'post_id' => $post_id,
'post_type' => $post_type
));
// Loop through the field groups
foreach ($field_groups as $field_group) {
// Get all fields associated wiht this group
$fields = acf_get_fields($field_group);
if ($fields) {
// loop through each field
foreach ($fields as $field) {
// Grab our needed values
$key_id = $field['key'] ?? false;
$name = $field['name'] ?? false;
$default = $field['default_value'] ?? false;
// Only apply to fields that have a name value (skips tabs etc)
if ($key_id && $name) {
// Save the field to the post with the default value
update_field($name,$default,$post_id);
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment