Fix ACF Bidirectional relations
-
Hi,
While working on a project, I found that if you clone a post that had a bidirectional connection to another post, the connection was correctly cloned the other post, but the connection back wasn’t made. This makes sense since you’re not touching that other post. ACF has had this bidirectional option for a while and cloning posts that use this, effectively breaks the connection from one side.
I wrote a function that hooks into your ‘duplicate_post_post_copy’ and resaved any bidirectional ACF field, which correctly creates the connection in both directions, fixing this issue. Is this something you’d consider adding to the plugin? Or would you tell me: create your own add-on plugin.
This is the function:
add_action('duplicate_post_post_copy', 'resync_bidirectional_fields_after_duplicate', 20, 2);
function resync_bidirectional_fields_after_duplicate($new_post_id, $post)
{
if (!function_exists('get_field_objects')) {
return;
}
$fields = get_field_objects($new_post_id, false);
if (empty($fields)) {
return;
}
foreach ($fields as $field) {
if (empty($field['bidirectional']) || empty($field['bidirectional_target']) || empty($field['value'])) {
continue;
}
delete_field($field['key'], $new_post_id);
update_field($field['key'], $field['value'], $new_post_id);
}
}
You must be logged in to reply to this topic.