Last active
January 19, 2024 00:41
-
-
Save jarodthornton/cd9a0398f77d053a83711012942f9a19 to your computer and use it in GitHub Desktop.
WordPress Shortcode to output Google My Business Hours
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Shortcode to output GMB hours | |
// Use [hours] shortcode | |
// By Jarod Thornton https://jarodthornton.com | |
// And Adopt the Web https://adopttheweb.com | |
function atw_gmb_hours() { | |
// Get Google Places ID here: https://developers.google.com/maps/documentation/places/web-service/place-id#save-id | |
// Input the Google Places ID here | |
$gmb_place_id = '_id_'; | |
// Input the API key here | |
$atw_key = '_your_key_'; | |
$url = 'https://maps.googleapis.com/maps/api/place/details/json?place_id='. $gmb_place_id .'&fields=opening_hours&key='. $atw_key; | |
$hours_raw = @file_get_contents($url); | |
if (!empty($hours_raw)) { | |
$hours_json = json_decode($hours_raw, true); | |
if (!empty($hours_json['result']['opening_hours'])) { | |
$business_open = $hours_json['result']['opening_hours']['open_now']; | |
$business_hours = $hours_json['result']['opening_hours']['weekday_text']; | |
} | |
} | |
ob_start(); | |
if ( $business_open == 1 ){ | |
echo '<span><strong>We Are Open Now</strong></span>'; | |
} else { echo '<span><strong>Sorry, We Are Closed</strong></span>'; } | |
echo '<p>Our Hours Are:</p><ul>'; | |
foreach ($business_hours as $weekday) { | |
echo '<li>' . $weekday . '</li>'; | |
} | |
echo '</ul>'; | |
$hours = ob_get_contents(); | |
ob_end_clean(); | |
return $hours; | |
} | |
add_shortcode('hours', 'atw_gmb_hours'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment