Last active
February 26, 2024 20:35
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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