Hello,
in the backend of a post I am trying to create another post with custom fields, then add the new post to an existing relationship field in the same set of fields of the first post.
Something like:
related_posts (relationship field)
I created an ACF form to manage related posts, and I would like to create a new related post on the fly in the same form.
I have a relationship field ‘related_posts’, then a True/False to ask “Do you want to create a new related post?”, conditional fields to write the title of the new post and add some other custom fields.
In my functions I managed to create the new post on save, but I’m not sure about how can add it to the related posts relationship field.
If I use this code
update_field('related_posts', $post_id);
the new post replaces ALL the posts that I had previously selected in my relationship field. How can I add the new post to the selected old posts, instead?
Thank you
Also, how can I reset/clear the values of previous fields that I used to write the name and other metadata after I save the post?
To update an existing relationship field to add a value you first need to get the existing value without formatting and then add the new post ID to it.
// get current value
$value = get_field('relationship_field', $post_id, false);
// add new id to the array
$value[] = $inserted_post_id
// update the field
update_field('relationship_field', $value, $post_id);
To delete existing values in the current post
delete_field('some_field', $post_id);
Thanks, it worked like a charm!
Just a note about deleting fields, in case someone needs it:
to delete a field inside a group i used this formula
groupname_fieldname
it works even if groups names and fields names already contain underscores, i.e.:
Group name: my_group
Field name: my_field
delete_field('my_group_my_field', $post_id);