Support

Account

Home Forums General Issues Clone a document and transfer ACF data Reply To: Clone a document and transfer ACF data

  • The problem with the code is that it assumes that any custom field that is an array value is a standard WP custom meta field with multiple db entries.

    
    foreach ($data as $key => $values) {
      // if you do not want weird redirects
      if($key == '_wp_old_slug') {
        continue;
      }
      foreach ($values as $value) {
        add_post_meta($inserted_post_id, $key, $value);
      }
    }
    

    ACF stores a lot of fields as serialized arrays, including information about the rows of a flex field. This code will break any ACF fields that expect an array to be stored.

    So you need to store standard WP fields the way that this is doing and you need to store ACF fields as the array that is originally returned.

    The following is a guess and I can’t guarantee it will work, it may still break something.

    
    // add before loop metadat loop
    restore_current_blog();
    
    foreach ($data as $key => $values) {
      // if you do not want weird redirects
      if($key == '_wp_old_slug') {
        continue;
      }
      
      // try to detect if this is an ACF field
      // this needs to be done on the original post
      $field = get_field_object($key, $post_id, false, false);
      
      // switch blog
      switch_to_blog($blog_id);
      
      if ($field) {
        // we think it's an acf field
        // preserve it in whatever format it is
        upate_post_meta($inserted_post_id, $key, $value);
      } else {
        // we think it's a regular WP field
        foreach ($values as $value) {
          add_post_meta( $inserted_post_id, $key, $value );
        }
      }
      // restore the blog so next loop can check the original post field
      restore_current_blog();
    }