Support

Account

Home Forums ACF PRO Clone field value from Relationship post

Solved

Clone field value from Relationship post

  • Hi,
    I have two custom post types, Events and Places. Every event has a post relationship field to assign the event to a place. Every place post has a Google Maps field (address). I want to fetch and clone the address field value from the related place to a separate adress field (event_address) on the event when I save the event.
    Can someone please point me in the right direction here?

    Thanks!

  • 
    add_action('acf/save_post', 'save_event_update_address', 20);
    function save_event_update_address($post_id) {
      if (get_post_type($post_id) != 'events') {
        // not and event post, bail
        return;
      }
      // get location post ID
      // you said it's a relationship field, a relationship field will turn an array of posts
      // I am setting the 3rd parameter because we only need the IDs
      $related_places = get_field('relationship_field_name', $post_id, false);
      if ($related_places) {
        $place_id = $related_places[0];
        $address = get_field('address_field_on_place_name', $place_id);
        update_field('address_field_on_event_name', $address, $post_id);
      }
    }
    
  • I know this is an old post and was solved, but wanted to ask, what if the Events fields were in repeater fields? I tried to modify as below, but not getting the right results.

    add_action('acf/save_post', 'save_event_update_address', 20);
    function save_event_update_address($post_id) {
      if (get_post_type($post_id) != 'events') {
        // not and event post, bail
        return;
      }
      // get location post ID
      // you said it's a relationship field, a relationship field will turn an array of posts
      // I am setting the 3rd parameter because we only need the IDs
      $related_places = get_sub_field('relationship_field_name');
      // also the 
      if ($related_places) {
        $place_id = $related_places[0];
        $address = get_field('address_field_on_place_name', $place_id);
        update_sub_field('address_field_on_event_repeater_name, $address, $post_id);
      }
    }
  • In order to update a sub field you must loop over the repeater in the same way that you’d loop over it when displaying values https://www.advancedcustomfields.com/resources/update_sub_field/

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

The topic ‘Clone field value from Relationship post’ is closed to new replies.