Hi there,
I am updating a relationship field on a post by using the update_field function.
If I edit the post in WP and add a new field there and save the post then the update_field function will work properly and update the field with new entries. However if the relationship field is empty it will not add new entries to it.
I can only guess this must be some sort of bug. Unless there is some sort of trick I’m not seeing somewhere.
Thanks!
Hi @rivage
So just to be clear, when you say “new entries” you mean selecting posts within the relationship field?
I think this is more an issue of how update_field works and how people expect it to work. Just like it sounds the function update_field are only capable of updating an existing meta value. When you have a new post (or where ever you placed the field) with nothing added to the field (nor anything previously added but now deleted) there is no meta key in the DB. So the update_field function fails.
What you can do instead is look at how the relationship-field saves the values to the DB. I’m fairly certain it’s just an array of IDs but take a look to be sure. Then you can use WP Core function update_post_meta instead and pass in values just like they would be saved by ACF.
Then it’ll work I’m sure.
Yep, that did the trick. Thanks!
Just had to switch update_field to update_post_meta and move the postid to the start and add serialize to the array.
serialize
http://php.net/manual/en/function.serialize.php
update_post_meta
http://codex.wordpress.org/Function_Reference/update_post_meta
No problem!
As a note you don’t actually have to serialize your array before as update_post_meta will do that for you. Just pass in your array and you’re good to go!