Skip to content

Instantly share code, notes, and snippets.

@wpeasy
Created October 7, 2024 00:42
Show Gist options
  • Save wpeasy/c5f57091aa17c63749aa0c3d8f1bb2a3 to your computer and use it in GitHub Desktop.
Save wpeasy/c5f57091aa17c63749aa0c3d8f1bb2a3 to your computer and use it in GitHub Desktop.
Bricks MetaBox Events Multi Timezone
document.addEventListener('DOMContentLoaded', () => {
// Function to convert Unix timestamp to local date time string
function convertUnixToLocalDateTime(unixTimestamp) {
const date = new Date(unixTimestamp * 1000); // Convert Unix timestamp to milliseconds
const options = {
month: 'long', // Full month name
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
hour12: true // AM/PM format
};
return date.toLocaleString('en-US', options);
}
// Query all elements with the data-timestamp attribute
const elements = document.querySelectorAll('[data-timestamp]');
// Iterate over each element
elements.forEach(element => {
// Get the data-timestamp attribute value
const unixTimestamp = element.dataset.timestamp;
// Convert the Unix timestamp to a formatted date time string
const formattedDate = convertUnixToLocalDateTime(unixTimestamp);
// Set the innerText of the element to the formatted date
element.innerText = formattedDate;
});
});
<?php
/*############################
DEBUGGING
###########################*/
define("WPE_TUT_DEBUG", false);
define("WPE_LOG_PATH", ABSPATH . 'wp-content/logs/');
function debug_log($object, $context = "")
{
if (WPE_TUT_DEBUG && class_exists("BugFu")) {
BugFu::log([$context, $object]);
}
}
function log_file($message){
if(!WPE_TUT_DEBUG) return;
// Define the log file path
$log_file = ABSPATH . 'wp-content/logs/WPCB.log';
// Ensure the logs directory exists
if (!file_exists(ABSPATH . 'wp-content/logs')) {
mkdir(ABSPATH . 'wp-content/logs', 0755, true); // Create the directory with proper permissions
}
// Format the log message with current time and message
$time = current_time('mysql'); // Get the current WordPress time in MySQL format
$formatted_message = "[{$time}] {$message}" . PHP_EOL;
// Write the message to the log file
file_put_contents($log_file, $formatted_message, FILE_APPEND | LOCK_EX);
}
/*############################
METABOX FUNCTIONS
###########################*/
function wpe_timezone_identifiers_list()
{
static $timezone_assoc;
if ($timezone_assoc) {
return $timezone_assoc;
}
debug_log("MetaBox call", __FUNCTION__);
$timezones = timezone_identifiers_list();
$timezone_assoc = array_combine($timezones, $timezones);
return $timezone_assoc;
}
/*############################
BRICKS SECURITY
###########################*/
/* Allow {echo:} functions */
add_filter("bricks/code/echo_function_names", function () {
return ["strtotime", "wpe_get_timestamp_from_string"];
});
/*############################
BRICKS ECHO FUNCTIONS
###########################*/
function wpe_get_timestamp_from_string($date_string, $timezone)
{
$tz = wpe_get_event_datetime_timezone(null);
if (!wpe_timezone_exists($tz)) {
debug_log("Missing or invalid Timezone", __FUNCTION__);
return "Missing or invalid Timezone";
}
// Create a DateTime object with the specified date string and timezone
$date = new DateTime($date_string, new DateTimeZone($timezone));
// Return the Unix timestamp as an integer
return $date->getTimestamp();
}
/*############################
UTILITY CLASSES
###########################*/
function wpe_get_event_datetime_timezone($post_id = null)
{
if (!$post_id) {
$post_id = get_the_ID();
}
debug_log($post_id, __FUNCTION__);
return get_post_meta($post_id, "event_timezone", true);
}
function wpe_get_event_date($post_id = null)
{
if (!$post_id) {
$post_id = get_the_ID();
}
debug_log($post_id, __FUNCTION__);
return get_post_meta($post_id, "event_date", true);
}
function wpe_timezone_exists($timezoneString)
{
// Get all valid timezone identifiers
$validTimezones = timezone_identifiers_list();
// Check if the provided timezone is in the list of valid timezones
return in_array($timezoneString, $validTimezones);
}
/* For Bricks Countdown */
function wpe_decimal_to_hours_minutes($decimalHours)
{
// Convert the decimal hours to total minutes
$totalMinutes = $decimalHours * 60;
// Get the number of whole hours
$hours = floor($totalMinutes / 60);
// Get the remaining minutes
$minutes = round($totalMinutes % 60);
// Format the result as HH:MM with zero padding
return sprintf("%02d:%02d", $hours, $minutes);
}
/*@see https://itchycode.com/some-powerful-filter-hooks-in-bricks-builder-you-might-not-know/ */
add_filter("bricks/element/settings", "itchy_change_element_settings", 10, 2);
function itchy_change_element_settings($settings, $element)
{
/* If the coundown ID is any of the array keys, getteh meta value */
if (!in_array($element->id, ["ewwndv"])) {
return $settings;
}
/* Check if the timezone exists and is valid. If not, just return the settings*/
$tz = wpe_get_event_datetime_timezone(null);
if (!wpe_timezone_exists($tz)) {
return $settings;
}
debug_log(
"Valid TZ for post_ID " .
get_the_ID() .
" - " .
$tz .
" : Applying to " .
$element->id,
__FUNCTION__
);
$countdown_end = wpe_get_event_date();
$countdown_end_object = new DateTimeImmutable(
$countdown_end,
new DateTimeZone($tz)
);
$settings["date"] = $countdown_end_object->format("Y-m-d H:i:s");
$offsetHours = $countdown_end_object->getOffset() / 60 / 60;
$symbol = $offsetHours > 0 ? "+" : "";
$settings["timezone"] =
"UTC" . $symbol . wpe_decimal_to_hours_minutes($offsetHours);
return $settings;
}
/*############################
EVENT CPT FUNCTIONS
###########################*/
/*
When saving an Event post:
Calculate the UTC0 timestamp and save it in the meta field _timestamp_utc
We will use this value to order the events in real order, not the date string
*/
add_action("save_post", "wpe_save_event_timestamp_utc", 10, 3);
function wpe_save_event_timestamp_utc($post_id, $post, $update)
{
// Check if the post type is 'event'
if ("event" !== $post->post_type) {
return;
}
// Check if this is a revision or an autosave
if (wp_is_post_revision($post_id) || wp_is_post_autosave($post_id)) {
return;
}
// Retrieve the event date and timezone
$event_date = wpe_get_event_date($post_id);
$event_timezone = wpe_get_event_datetime_timezone($post_id);
// Ensure both fields are present
if (!$event_date || !$event_timezone) {
return;
}
log_file('CONVERT: '. $event_date . ' -- ' . $event_timezone);
try {
// Create DateTime object from event_date and set the correct timezone
$date = new DateTime($event_date, new DateTimeZone($event_timezone));
// Convert to UTC by setting the timezone to UTC
$date->setTimezone(new DateTimeZone("UTC"));
// Get the UTC timestamp as an integer
$utc_timestamp = $date->getTimestamp();
log_file('TIMESTAMP_UTC: '. $utc_timestamp);
// Save the UTC timestamp as a meta field
update_post_meta($post_id, "_timestamp_utc", $utc_timestamp);
} catch (Exception $e) {
// Handle errors with date conversion if necessary
error_log(
"Error calculating UTC timestamp for event: " . $e->getMessage()
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment