Support

Account

Home Forums General Issues Add taxonomy terms to custom post type from posts in relationship field

Solving

Add taxonomy terms to custom post type from posts in relationship field

  • Hello,

    I have two CPT’s – “Resource” and “Publication”. Both share similar taxonomy’s, “Type” for example. “Publications” can be linked to “Resources” via an ACF relationship field using post objects.

    Is there a way to add the taxonomy terms from the “Publications” to the “Resource” when the pubs posts are added via the relationship field? So the “Resource” would inherit all the “Types” from the pubs contained within, as it were?

    Thanks!

  • I’m a little confuse about which way you want to add.

    But you could

    1. create an acf/save_post action
    2. Get the terms of the post being saved
    3. Loop over the relationship field and get the terms for each post
    4. use wp_add_object_terms() to update either/or the side you want to inherit the terms from

    The above is simplified because you’d probably also want to deal with when relationships are removed or terms are updated on one site or the other. This can get complicated because you’d have to track both what the terms on each side were and what they are being changed to.

  • Thanks John, I think that makes sense. I reckon I could do steps 1-4, but yeah I’m not sure how I’d go about dealing with the adding/removing and terms being updated. Any code examples for this greatly appreciated!

  • This isn’t something I’ve ever tried before, but it would mean having a priority of < 10 on the filter so that you can compare the current value of the relationship field with the previous value of the relationship field.

    There is an example of doing this for biderectional relationship fields https://www.advancedcustomfields.com/resources/bidirectional-relationships/

    But the problem is that you’re dealing with terms, so more than one relationship would be involved. The same terms could be added by other relationship fields.

    So I would amend my previous steps. First off you would need to set up a bidirectional relationship field. You would also need to check all of the posts that are related to all of the posts in the relationship field 2 steps away

    
    current post => relationship field => related posts relationship fields
    

    to figure out what should be added/removed.

    Thinking about it makes my head hurt a bit. I’m sure it’s possible but would take me several hours to work out the details.

  • Thanks John!

    It’s also making my head hurt, but I’m gonna give it a go and I’ll post my results here if I can get it working….

Viewing 5 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic.