Skip to content

Snippets / PHP

PHP

Auto-Populate Event Location in WordPress Based on Related Post

A Accursio · 156 views · Updated 1 year ago
Description of the CodePurpose: 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 · 22 lines

Discussion

Ask a question or share how you used this.

Log in to join the discussion.

No comments yet — be the first.

Voxel Guide assistant
Ask about snippets, addons & how-tos

Hey — how can I help?

I can dig through the library for snippets, addons, and tutorials.

AI can be wrong — double-check anything important.