Last active
May 19, 2016 10:20
-
-
Save evaqas/dd388d4fac12b7afb2bd21209b34bc8a to your computer and use it in GitHub Desktop.
Advanced Custom Fields bi-directional relationship
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Set bi-directional post type relationship | |
*/ | |
add_filter( 'acf/update_value/type=relationship', 'themeslug_acf_bidirectional_relationship', 10, 3 ); | |
function themeslug_acf_bidirectional_relationship( $value, $post_id, $field ) { | |
$allowed_field_names = array( 'car_model', 'car_make' ); | |
$field_name = $field['name']; | |
$remote_name = ( 'car_model' === $field_name ) ? 'car_make' : 'car_model'; | |
if ( ! in_array( $field_name, $allowed_field_names ) ) return $value; | |
remove_filter( 'acf/update_value/type=relationship', 'themeslug_acf_bidirectional_relationship', 10, 3 ); | |
// add current post_id to remote value | |
if ( ! empty( $value ) && is_array( $value ) ) { | |
foreach ( $value as $remote_id ) { | |
$remote_value = get_field( $remote_name, $remote_id, false ); | |
$remote_value = ( ! empty( $remote_value ) ) ? $remote_value : array(); | |
if ( ! in_array( $post_id, $remote_value ) ) { | |
$remote_value[] = $post_id; | |
update_field( $remote_name, $remote_value, $remote_id ); | |
} | |
} | |
} | |
$old_value = get_field( $field_name, $post_id, false ); | |
if ( ! empty( $old_value ) && is_array( $old_value ) ) { | |
foreach ( $old_value as $remote_id ) { | |
// if remote_id from old value is not found in the current new value array, we remove it | |
$value = ( ! empty( $value ) ) ? $value : array(); | |
if ( ! in_array( $remote_id, $value ) ) { | |
$remote_value = get_field( $remote_name, $remote_id, false ); | |
if ( ! empty( $remote_value ) && is_array( $remote_value ) ) { | |
$pos = array_search( $post_id, $remote_value ); | |
unset( $remote_value[ $pos ] ); | |
update_field( $remote_name, $remote_value, $remote_id ); | |
} | |
} | |
} | |
} | |
add_filter( 'acf/update_value/type=relationship', 'themeslug_acf_bidirectional_relationship', 10, 3 ); | |
return $value; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment