Home › Forums › General Issues › Updating metadata (in bulk) the right way
Hello all,
Hope you’re doing well!
I’m trying to pull the data of a meta_value
, which is a raw url (an attachment), then convert it to an integer ID (the attachment ID), to then update a new custom field made with ACF.
What would be the best way to do this in bulk?
I’ve tried the following code with no success (please note I’m not a developer).
add_action('acf/save_post', 'pet_adoption_fund_update_meta');
function pet_adoption_fund_update_meta( $post_id ) {
// $file_route will return an url, like so: http://example.com/wp-content/uploads/2021/01/dogs_and_cats.jpg
$file_route = get_post_meta( get_the_ID(), 'volunteer_profile_file', true );
$file_id = '';
$file_id = attachment_url_to_postid( $file_route );
if ( empty( get_field( 'volunteer_attachment' ) ) ) { // ACF field. Don't update if already it's been filled in.
update_post_meta( $post_id, 'volunteer_attachment', $file_id );
}
}
While this seems to work (on save), this is not always the case. I’m unsure if this code is right and also I fear editing hundreds of entries.
How can I correctly update this metadata for all posts?
Any help is much appreciated.
Thank you in advance,
If you have a URL stored then how you are attempting to get the ID is the only way that I know of to do this.
As far as bulk updating this would be very difficult for someone that has experience, I would not attempt this.
I would create code similar to what you have for when the post is updated, except that I would move the check to see if there is a value before I did any work
// put at top of function
if (!empty( get_field('volunteer_attachment', $post_id))) {
// ACF field. Don't update if already it's been filled in.
return;
}
Then try to get the ID value. When you update you need to use update_field() with the field key (not the field name) because it is an image field that does not already have a value.
update_field('field_XXXXXXX', $file_id , $post_id)'
Once this is in place I would alter my theme file to use the new value and use the old value if the new field does not have a value
if (get_field('new_field_name')) {
// new field has a value, use it here
} else {
// new field has no value, get value of old field and use it instead
}
You must be logged in to reply to this topic.
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.