Skip to content

Instantly share code, notes, and snippets.

@wesrice
Created January 2, 2012 19:58
Show Gist options
  • Save wesrice/1551880 to your computer and use it in GitHub Desktop.
Save wesrice/1551880 to your computer and use it in GitHub Desktop.
ACF Reciprocal Relationship Functionality
<?php
function update_value( $post_id, $field, $value ){
// Check to see if there are any old relationships
if( parent::get_value( $post_id, $field ) !== '' ){
// If so, find out what needs to be added or deleted
$old_value = explode( ',', parent::get_value( $post_id, $field ) );
$new_value = explode( ',', $value );
// Determine which posts we need to remove the reciprocal relationships to
$posts_to_remove_relationships_from = array_diff( $old_value, $new_value );
// Determine which posts we need to add the reciprocal relationships to
$posts_to_add_relationships_to = array_diff( $new_value, $old_value );
} else {
// There are no old relationships, so the are all new
$posts_to_remove_relationships_from = array();
$posts_to_add_relationships_to = explode( ',', $value );
}
// Add relationships
foreach( $posts_to_add_relationships_to as $post_to_add_relationship_to ){
// Get the current value of the related post
$related_post_relationships = explode( ',', get_post_meta( $post_to_add_relationship_to, $field['name'], true ) );
if( $related_post_relationships[0] === '' ){
// This is post is new to relationships. Just add this post id
$related_post_relationships = array( $post_id );
} else {
// If the current post id isn't already related, append it to the list
if( ! in_array( $post_id, $related_post_relationships ) ) {
$related_post_relationships[] = $post_id;
}
}
// Create a string out of the results
$related_post_relationships = implode( ',', $related_post_relationships );
// Update the related post
update_post_meta( $post_to_add_relationship_to, $field['name'], $related_post_relationships );
}
// Remove relationships
foreach( $posts_to_remove_relationships_from as $post_to_remove_relationship_from ){
// Get the current value of the related post
$related_post_relationships = explode( ',', get_post_meta( $post_to_remove_relationship_from, $field['name'], true ) );
// Loop through the array, and unset the post id
foreach( $related_post_relationships as $key => $related_post_relationship ){
if( (int) $related_post_relationship === (int) $post_id ){
unset( $related_post_relationships[$key] );
}
}
$related_post_relationships = implode( ',', $related_post_relationships );
// Update the related post
update_post_meta( $post_to_remove_relationship_from, $field['name'], $related_post_relationships );
}
// Save Value
parent::update_value( $post_id, $field, $value );
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment