Home Forums General Issues Programmatically clear field values for all posts?


Programmatically clear field values for all posts?

  • I have a relationship field called related_posts associated with a custom post type called resource. I want to clear the value of that field for all existing posts, and I’m wondering how I might do so programmatically? It looks like I can use the delete_field function and just loop over all posts as detailed in the example included in that article- I’m wondering though (1) Will that work with a relationship field? and (2) What WordPress/ACF hook would I use in conjunction with that function to basically run it once to clear out the field data?

    Thanks for any guidance here.

  • There isn’t any such thing as a “run once ever” mechanism in WP.

    In addition to this, if you have many posts then looping over all of them to delete the field will more then likely time out.

    This is the way I deal with this.

    add_action('init', 'MY_FUNCTION_NAME');
    function MY_FUNCTION_NAME() {
      if (!is_user_logged_in() || get_current_user_id() != XX) {
        // replace XX with your user ID
        // only run this for me when I am logged in
      // query all posts
      // use your field name in meta query
      // only get posts where the meta_key "EXISTS"
      // loop over results and delete_field() on each

    If you have a lot of posts then this will time out the page load. If this happens reload the page until it not longer does so. This will indicate that the field has been deleted from all posts.

  • Thanks for your reply, @hube2 – I ended up using the init hook as indicated in your example, and I also made use of the add_option() / get_option() functions to force the utility function to run only once, as described in this post. For any others who may stumble across this thread and need to do something similar (e.g. utility function to update the content of a field for all posts), this approach worked well for me.

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

You must be logged in to reply to this topic.