This site is running Voxel Theme Version: 1.6.1.2 | Elementor Plugin Version: 3.32.3

Join the Voxel Guide Community!

Get Involved

Automatically get child CPTs location from parent CPT location field

Description/Instructions

Automatically get / save / update child CPTs location from parent CPT location field.

Instructions

Places CPT (key "places") has many Events CPT (key "events")
Events CPT (key "events") belongs to one Places CPT (key "places")

Be sure that both CPTs location fields have the key "location" and post relation key as "post-relation".
Adjust it for your specific needs.

// Hook for when events are submitted/updated
add_action( 'voxel/app-events/post-types/events/post:submitted', 'update_event_location' );
add_action( 'voxel/app-events/post-types/events/post:updated', 'update_event_location' );

// Hook for when places are updated
add_action( 'voxel/app-events/post-types/places/post:updated', 'update_related_events_location' );
// Hook for when places are submitted (only if necessary)
// add_action( 'voxel/app-events/post-types/places/post:submitted', 'update_related_events_location' );

function update_event_location( $event ) {
$post = $event->post;

// Ensure the post type is 'events'
if ( $post->post_type->get_key() !== 'events' ) {
return;
}

// Get the related post ID from the 'post-relation' field
$relation_id = $post->get_field('post-relation')->get_value()[0] ?? null;

if ( $relation_id ) {
// Retrieve and update the 'location' field if it exists
$location = json_decode( get_post_meta( $relation_id, 'location', true ), true );
if ( $location ) {
$post->get_field('location')->update( $location );
}
}
}

function update_related_events_location( $event ) {
global $wpdb;

$post = $event->post;

// Ensure the post type is 'places'
if ( $post->post_type->get_key() !== 'places' ) {
return;
}

$place_id = $post->get_id();
$location = json_decode( get_post_meta( $place_id, 'location', true ), true );

if ( ! $location ) {
return;
}

// Query the custom relations table to find events related to this place
$table_name = $wpdb->prefix . 'voxel_relations';
$event_ids = $wpdb->get_col( $wpdb->prepare(
"SELECT child_id FROM {$table_name} WHERE parent_id = %d",
$place_id
) );

if ( empty( $event_ids ) ) {
return;
}

// Update location for each related event
foreach ( $event_ids as $event_id ) {
$voxel_event = \Voxel\Post::get( $event_id );
if ( $voxel_event && $voxel_event->post_type->get_key() === 'events' ) {
$voxel_event->get_field('location')->update( $location );
}
}
}

  • PHP
Copy Code

Let's Chat About this Snippet

Chat Toggle
Voxel Guide AI
Voxel Guide AI
Voxel Guide AI
Voxel Guide AI
Ask me anything about Voxel!
Send
Powered by AI24