Skip to content

Instantly share code, notes, and snippets.

@andrasguseo
Created July 22, 2024 14:15
Show Gist options
  • Save andrasguseo/d369316c1ad94ab01e0b2b04f062356b to your computer and use it in GitHub Desktop.
Save andrasguseo/d369316c1ad94ab01e0b2b04f062356b to your computer and use it in GitHub Desktop.
TEC > Generate a UID for the event and add it to the iCal feed.
<?php
/**
* Description: Generate a UID for the event and add it to the iCal feed.
* Usage: Paste the below snippet into your active (child) theme's functions.php file
* or use a plugin like Code Snippets.
*
* Plugins: The Events Calendar
* Author: Andras Guseo
* Last updated: 2024-07-22
*/
add_filter( 'tribe_ical_feed_item', 'my_custom_uid', 10, 2 );
/**
* Add the UID of the event to the feed.
*
* @param array $item The event data currently being processed.
* @param WP_Post $event_post The event object.
*
* @throws \Random\RandomException
* @return array The modified event data.
*/
function my_custom_uid( $item, $event_post ) {
$post_id = $event_post->ID;
$post_uid = get_post_meta( $post_id, '_eventUID', true );
// If there is no UID, generate one, save it with the post and use it in the feed.
if ( ! $post_uid ) {
$post_uid = generate_uid();
while ( check_if_uid_exists( $post_uid ) ) {
$post_uid = generate_uid();
}
// Save it with the post.
add_post_meta( $post_id, '_eventUID', $post_uid, true );
}
$item['UID'] = 'UID:' . $post_uid;
return $item;
}
/**
* Generate a UID like 5FC53010-1267-4F8E-BC28-1D7AE55A7C99
*
* @throws \Random\RandomException
* @return string
*/
function generate_uid() {
try {
// Generate 16 bytes (128 bits) of random data
$data = random_bytes( 16 );
}
catch ( Exception $e ) {
// Log the exception message or handle it in some way
error_log( 'Failed to generate random bytes: ' . $e->getMessage() );
// Rethrow the exception
throw $e;
}
// Set the version to 4 (random UUID).
$data[6] = chr( ord( $data[6] ) & 0x0f | 0x40 );
// Set the variant to RFC 4122
$data[8] = chr( ord( $data[8] ) & 0x3f | 0x80 );
// Convert the binary data into hexadecimal representation.
$hex = bin2hex( $data );
// Format the hex into the UUID format: 8-4-4-4-12.
$uuid = sprintf( '%s-%s-%s-%s-%s',
substr( $hex, 0, 8 ),
substr( $hex, 8, 4 ),
substr( $hex, 12, 4 ),
substr( $hex, 16, 4 ),
substr( $hex, 20, 12 )
);
return strtoupper( $uuid );
}
/**
* Check if UID exists.
*
* @param string $uid The UID of the event.
*
* @return bool True if post with UID exists.
*/
function check_if_uid_exists( $uid ) {
$args = [
'meta_key' => '_eventUID',
'meta_value' => $uid,
'post_type' => 'tribe_events',
'fields' => 'ids',
'numberposts' => 1,
];
$posts = get_posts( $args );
return ! empty( $posts );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment