Home Forums Backend Issues (wp-admin) Programmatically add relationship field data


Programmatically add relationship field data

  • I am trying to map an ACF Relationship field during the post creation process via GravityForms form. For most fields I can use a snippet of code as follows:

    add_action('gform_advancedpostcreation_post_after_creation_7', function ($post_id, $feed, $entry, $form) {
    $acf_field = rgar( $entry, '17' );
    update_field( 'field_63d65a709cc93', $acf_field, $post_id );
    }, 10, 4 );

    However, for relationship fields this method does not work.

    I’m sure I’m missing something very simple! Any pointers would be much appreciated.


    NB: The relationship field is set-up to allow only a single selection.

  • A relationship field holds and array of ID values

    // if the might already have a value
    $value = get_field('field_63d65a709cc93', $post_id);
    if (empty($value)) {
      $value = array();
    $value[] = intval(rgar($entry,'17'););
    update_field('field_63d65a709cc93', $value, $post_id);
  • Hi, John –

    Thank you for your support. For some reason this isn’t working. I suspect it’s because I have the relationship field set-up to return the Post Object – not the Post ID. Would this make a difference?

    I’ve tried changing it over to return the Post ID but that just creates huge knock effects for the rest of the site – and I don’t want to make my task any more complicated than it is already!

  • my mistake, you need to get the current value unformatted, do this

    $value = get_field('field_63d65a709cc93', $post_id, false);
  • John –

    Thanks again but that won’t work because it has to get the value from the form:

    $value[] = intval(rgar($entry,'16'));

    If I just put a clean number into the value it works perfectly:

    $value = "1234"

    I need to get the related post ID from this (which is returning the Post Object):


  • I have no idea what rgar() is. but if it’s returning a post object then this might work

    $post = rgar($entry,'16');
    $post_id = $post->ID;
Viewing 7 posts - 1 through 7 (of 7 total)

You must be logged in to reply to this topic.