I’ve had this problem for a while, on multiple sites, and am wondering if anyone has a solution. I use the bidirectional relationships snippet to relate posts in two different custom post types. It *almost* works perfectly except the relationship doesn’t show up on the frontend for the second post until it too is updated. Instead I get this PHP notice:
: Undefined offset: 0 in
If I do a print_r on the field, I get an empty array. As soon as I update the second post, that goes away, the relationship shows up fine on the frontend, and print_r returns an array of the post ids.
Is there any fix for this so that I don’t have to resave both posts? That kind of defeats the purpose of the otherwise awesome bidirectional relationships snippet.
If you are updating the value on the other end where a value was not previously stored by ACF and you are using the field name when calling update_value() then this will cause the problem you are seeing. When you use update_field() on a field that has never been saved before then you must use the field key instead of the field name. This in explained in the documentation https://www.advancedcustomfields.com/resources/update_field/
Also this is mine and works where the field names are the same and it deals with the keys. https://wordpress.org/plugins/post-2-post-for-acf/. The reason that it works is that it basically reads thought all of the ACF fields to find all the fields with the same name and then uses the key…. well, it actually uses update_post_meta() and bypasses the acf function completely. It also has some other features like checking the max number of posts that the field on the other side of the relationship can have so it won’t have too many.
The basic code will work where you use the same field, basically a field group with one field for the relationship where you have the group on multiple post types. It’s really designed for the same field in the same field group.