ACF Relationship Sync

I use Advanced Custom Fields for many projects here at Fancy Fiber Designs to make some pretty advanced website functions. You may have already seen our plug-in for Advanced Custom Fields as well to allow you to add a new related field without leaving the post you are editing. There are also times that we need have wanted to keep our relationship fields in-sync with each other, where there are two custom post types that are related to each other and they both need to know about the relationship. For example, a public speaker needs to have an agent. They both need to be related to each other. If the speaker drops the agent, or the agent drops the speaker, we don’t want to have to have the user update the both the agent and the speaker custom post type. They are able to edit in one place and have the change sync to the other. This is not a default function of Advanced Custom Fields however. I’ll show you how to do it though.

This assumes that you have already created your custom post types for Speakers and Agents and created your Advanced Custom Fields relationship fields for the speakers and agents. I used ‘speaker_agent’ for the Speaker relationship to the agent, and ‘speaker_managed’ for the Agent relationship to the speaker.

First we need an action on the Advanced Custom Fields Save Post:

This action will call our function when Advanced Custom Fields does it’s processing of saving a post. Then we create our save post function:

First, we get the post type of the post being saved to make sure we only run on the proper custom posts. If it is a speaker or an agent post being saved, we call our relationship sync code with the proper arguments. Then, the most important part of the process; the actual code to perform the relationship sync:

This function takes the relationships you have defined and updates the post meta information. First it gathers the information that was just saved by Advanced Custom Fields for the relationship field. It also gathers the previous information stored for this relationship, which is not part of Advanced Custom Fields processing, but needed to keep things properly sync’d.

Then, we loop through the post ids in the from field and add this post id to those fields.

Finally, we loop through the previous post ids and see if any were removed, and remove them from the associated posts and save our previous information for the next time.

 

This entry was posted in Coding, PHP, WordPress and tagged , , , , , , . Bookmark the permalink.

Comments are closed.