Skip to content

Instantly share code, notes, and snippets.

@pixelwatt
Last active February 18, 2020 21:47
Show Gist options
  • Save pixelwatt/bb9bb72010c53aeee5e97ae784dc422a to your computer and use it in GitHub Desktop.
Save pixelwatt/bb9bb72010c53aeee5e97ae784dc422a to your computer and use it in GitHub Desktop.
Associate Wordpress Posts from Two Different Custom Post Types
<?php
// For the custom post type 'communities', a custom option exists to allow editors to select 'plans' (from another custom post type) that are associated with the community post. Depending on data being displayed on the frontend, storing this data with 'plans' can potentially eliminate expensive database queries from being neccessary, especially in reguards to AJAX search. The function below syncs data with associated 'plan' posts once a community is saved or updated. This does not take into account certain scenarios, such as plans being trashed or restored. Ideally, you'd take those into account and also add a cleanup task to wp_cron to occasionally unset and rebuild the associations.
function sync_community_data( $id, $post ) {
if ( ( 'communities' == $post->post_type ) && ( $id ) ) {
$associated = get_post_meta( $id, 'plans', true );
$associated = ( is_array( $associated ) ? $associated : array() );
// First, find plans currently tied to the community, and remove the community ID if the plan is no longer associated
$args = array(
'post_type' => 'plans',
'meta_query' => array(
array(
'key' => 'communities',
'value' => $id,
'compare' => 'LIKE'
)
)
);
$plans = get_posts( $args );
if ( ! empty( $plans ) ) {
if ( is_array( $plans ) ) {
foreach ( $plans as $plan ) {
if ( ! in_array( $plan->ID, $associated ) ) {
$plan_communities = get_post_meta( $plan->ID, 'communities', true );
$key_to_unset = array_search( $id, $plan_communities );
array_splice( $plan_communities, $key_to_unset, 1 );
update_post_meta( $plan->ID, 'communities', $plan_communities );
}
}
}
}
// Now, add the community ID to associated plans
if ( ! empty( $associated ) ) {
foreach ( $associated as $plan ) {
$plan_communities = get_post_meta( $plan, 'communities', true );
if ( is_array( $plan_communities ) ) {
$pre_existing = array_search( $id, $plan_communities );
if ( false === $pre_existing ) {
$plan_communities[] = $id;
update_post_meta( $plan, 'communities', $plan_communities );
}
} else {
$new_array = array();
$new_array[] = $id;
update_post_meta( $plan, 'communities', $new_array );
}
}
}
}
return;
}
add_action( 'save_post', 'sync_community_data', 10000, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment