Created
March 15, 2018 15:32
-
-
Save mrksdiehl/38a69463b17e0cd844a67cb22af257ac to your computer and use it in GitHub Desktop.
Sync two posts if both use carbon fields association
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 | |
/** | |
* Sync the association field between a post and the associated | |
* post_tpes. To be used during carbon_fields_post_meta_container_saved | |
* | |
* @param string $post_id The post id of the post that is being saved | |
* @param string $key The carbon fields key of the association field | |
* @param array $target carbon fields 'key' and 'post_type' of the target | |
* @return void | |
*/ | |
function carbon_sync_posts( $post_id, $key, $target ) { | |
$source_post_type = get_post_type( $post_id ); | |
//// Get field values | |
$source_values = carbon_get_post_meta( $post_id, $key); | |
//// The source value field | |
$source_value = 'post:' . $source_post_type . ':' . $post_id; | |
//// Get all targets | |
$target_posts = get_posts([ | |
'post_type' => $target['post_type'], | |
'numberposts' => -1, | |
'posts_per_page' => -1 | |
]); | |
foreach( $target_posts as $post ) { | |
$target_value = 'post:' . $target['post_type'] . ':' . $post->ID; | |
$target_values = carbon_get_post_meta( $post->ID, $target['key'] ); | |
$entry_exists_in_target = count( array_filter( $target_values, function( $entry ) use ($source_value){ | |
return $entry['value'] == $source_value; | |
})) > 0; | |
$entry_should_be_in_target = count( array_filter( $source_values, function( $entry ) use ($target_value){ | |
return $entry['value'] == $target_value; | |
})) > 0; | |
//// Add if not in target | |
if ( ! $entry_exists_in_target && $entry_should_be_in_target ) { | |
carbon_set_post_meta( $post->ID, $target['key'], [ 'value' => $source_value ] ); | |
} | |
//// Remove if in target but removed from source | |
if ( $entry_exists_in_target && ! $entry_should_be_in_target ) { | |
$new_entries = array_map( function( $entry ) use ( $source_value ) { | |
if ( $entry['value'] !== $source_value ) { | |
return [ 'value' => $entry['value'] ]; | |
} | |
}, $target_values); | |
carbon_set_post_meta( $post->ID, $target['key'], $new_entries); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment