Skip to content

Instantly share code, notes, and snippets.

@omelsoft
Last active October 7, 2017 04:48
Show Gist options
  • Save omelsoft/7f5c163d1986e8983e3b66f536b30b01 to your computer and use it in GitHub Desktop.
Save omelsoft/7f5c163d1986e8983e3b66f536b30b01 to your computer and use it in GitHub Desktop.
How to Update and Save Advance Custom Fields data within a Wordpress Loop
<?php
/**
* The purpose of this is that I was using an old Wordpress theme which generates a custom fields. Those fields will only be available
* when that theme is active. So when switching theme, all the posts meta data will not be inherited by the new theme.
*
* Note: Old theme is currently active
*
* So, I decided to use Advance Custom Fields and created fields for each keys used by the old theme. I was able to retrieve the key-values
* from the old theme and saved the values to the newly created ACF fields by iterating over each post. By simple using a sample snippet:
*
* update_field('is_post_review', 'yes', $post->ID);
*
* The above code updates the value which you can verify in the backend by looking at the ACF custom metabox field.
* But when I tried to retrieve the value in the front-end using get_field('is_post_review') I get an empty result.
* The value will only be available in the front-end when you save the post again in the backend.
*
* I did a quick search and found that ACF values are mapped into a unique field keys.
*
* So, first I retrieved the unique keys for each fields and assigned to an array which looks like the following.
*
* $keys['is_post_review'] = 'field_jkh123j123g';
*
* Here's the following code which does the trick.
*/
// You can change the $group_ID to your own
$group_ID = 6776;
$fields = array();
$fields = apply_filters('acf/field_group/get_fields', $fields, $group_ID);
$keys = array();
if( $fields )
{
foreach( $fields as $field )
{
$keys[$field['name']] = $field['key'];
}
}
$posts = query_posts(
array(
'post_type' => 'post',
'posts_per_page' => 500
)
);
foreach($posts as $post) {
update_field($keys['is_post_review'], 'no', $post->ID);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment