Join the Voxel Guide Community!

Get Involved

Auto-Populate Event Location in WordPress Based on Related Post

Description/Instructions

Description of the Code
Purpose: Automatically updates the “location” field of an event post based on the “location” metadata of a related post (e.g., a bar or restaurant organizing the event).
Triggers:The function update_event_location is executed when an event post is submitted or updated.
Process:Verifies that the post type is events.
Extracts the related post ID from the custom field post-relation.
Retrieves the location metadata (stored as JSON) from the related post.
Decodes the JSON data and updates the location field in the current event post.
Compact Logic: The function is designed to handle the process efficiently, with clear validations and minimal overhead.

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' );

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 );
}
}
}

  • 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