Using PHP to Show Google My Business Hours on Website

Keeping your Google My Business opening hours up to date is helpful to your customers, and we wanted to show a customer’s hours on their Joomla! website. We didn’t find and extension to help us with this, but did find a response in StackExchange. The code is straight forward; however, you have to have “billing” enabled in your Google Developers Console. We used a Gift Credit Card to get the account started.

Getting Started:

  • Google API Key: Create a project in the Google API Console and enable the Places API.
  • Enable Billing: The Places API requires an active billing account.
  • Place ID: Find your business’s Place ID using the Google Place ID Finder. 

Here is the code we used.

<?php
// Define your API Key and Place ID
define('GOOGLE_API_KEY', 'YOUR_API_KEY');
define('GOOGLE_PLACE_ID', 'YOUR_PLACE_ID');

// API endpoint URL for place details, requesting only opening hours
$url = 'https://maps.googleapis.com' . GOOGLE_PLACE_ID . '&fields=opening_hours&key=' . GOOGLE_API_KEY;

// Fetch the data from the Google Places API
$hours_raw = @file_get_contents($url);

if (!empty($hours_raw)) {
    $hours_json = json_decode($hours_raw, true);

    // Check if the request was successful and hours are available
    if (isset($hours_json['result']['opening_hours']['weekday_text'])) {
        $business_hours = $hours_json['result']['opening_hours']['weekday_text'];

        // Display the hours in an HTML list
        echo '<h3>Business Hours:</h3>';
        echo '<ul>';
        foreach ($business_hours as $weekday_hours) {
            echo '<li>' . htmlspecialchars($weekday_hours) . '</li>';
        }
        echo '</ul>';
    } else {
        echo 'Could not retrieve business hours or hours are not specified.';
    }
} else {
    echo 'Error fetching data from the Google API. Check your API key and network connection.';
}
?>

Let us know if this helped you…

Comments

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Translate »