Automatically set the value of a custom field in the intermediary post when connecting two existing posts in a M2M relationship

A M2M relationship has been created between two custom post types, and a custom field has been added to the relationship. When connecting two existing posts in wp-admin, you will be presented with a dialog where you can set the value of the custom field manually. This works fine, but let’s say you want to set the value of the custom field to be equal to the intermediary post’s ID. It’s not easy to do manually, so you want to set up some code that does this automatically. The save_post hook that could be used to do this in the legacy post relationship system will no longer work because the value set in the dialog will be savedĀ after the save_post hook – effectively overriding the assignment you created in code. This code worked before, but no longer works:

add_action( 'save_post_concert-band', 'auto_fill_concertband_sort', 10);
function auto_fill_concertband_sort( $post_id ) {
  $hasValue = types_get_field_meta_value( 'bc-sort-order', $post_id );
  if ( empty( $hasValue ) ) {
    update_post_meta( $post_id, 'wpcf-bc-sort-order', $post_id, true ); // this will be overridden by the value from the GUI
  }
}

The updated code relies on the hook wpcf_fields_value_save to perform similar actions.

// automatically set the value of the custom field to be intermediary post id
add_filter('wpcf_fields_value_save','autoupdate_sortorder_fields',1000,5);
function autoupdate_sortorder_fields($value, $type, $slug, $cf, $obj ){
  if($slug=='bc-sort-order'){
    $object_ID=$obj->post->ID;
    return $object_ID;
  }
  return $value;
}

This code will set the value of the custom field to equal the intermediary post ID, and only works if you do not plan to change this value in the future.