Home Forums ACF PRO Better way to update multiple fields (update_field())


Better way to update multiple fields (update_field())

  • At the moment, I’ve got a cron running which imports about 500 posts a day, with each post then having to use 10 update_field calls to update it’s custom fields.

    This obviously is quite slow as it runs about 5000 add_metadata DB calls taking around 50 seconds.

    Is there a more efficient way to do this?

  • That depends on how good you are at MySQL queries and using $wpdb

    for example a single query can insert multiple values all at once

    INSERT INTO wp_postmea (post_id, meta_key, meta_value) VALUES ("1", "field_1", "value_1"),("1", "_field_1", "field_0123456789"),..... etc.

    If you’re interested, you’d need to do a couple things.

    1) the best thing you can do is to delete all the meta values for the post first. The main reason that WP is so slow at inserting/updating post meta is that it checks every value to see if it already exists for the post or not and then either updates or inserts as needed. By deleting them all first you remove the need to check. You can’t use an INSERT IGNORE query because there’s nothing to indicate unique values in the postmeta table.

    2) you need to make sure you insert the ACF field references for each field as well as the value, like the second value in my example.

  • Perfect! Managed to reduce the amount of queries drastically.

  • I have often thought about building something that would bypass then entire ACF save routine by doing something similar.

    The main problem that I’ve found is that there is nothing to keep ACF from running anyway. Well there is, after the update you can unset $_POST[‘acf’], but there are other time consuming problems…

    … like you’d need to recreate most of the things that ACF does and deal with all the special fields involved and how each one needs to be stored, and then there’s the dealing with all of the custom field addons that exist and any special treatment you’d need to give those fields…

    What’s really needed is an improved mechanism in WP core for updating meta values that does not require doing multiple queries for every value, but I don’t think that’s ever going to happen.

Viewing 4 posts - 1 through 4 (of 4 total)

The topic ‘Better way to update multiple fields (update_field())’ is closed to new replies.