Google Places API Review Summary
November 28, 2024 · AI Conversations
### Step 1: Get an API Key
1. Go to the [Google Cloud Console](https://console.cloud.google.com/).
2. Create a new project or select an existing one.
3. Enable the **Places API** for your project.
4. Create an API key by navigating to **APIs & Services > Credentials** and clicking on **Create credentials > API key**.
### Step 2: Use the Google Places API
You can retrieve the details of a place, including total reviews and ratings, by making a request to the Google Places API.
Here’s an example of how you can do this using PHP:
<?php
function getPlaceDetails($placeId, $apiKey) {
// URL for Google Places API
$url = "https://maps.googleapis.com/maps/api/place/details/json?place_id={$placeId}&key={$apiKey}";
// Make the API request
$response = file_get_contents($url);
$data = json_decode($response, true);
// Check if the request was successful
if ($data['status'] === 'OK') {
// Extract rating and user reviews count
$rating = $data['result']['rating'] ?? null;
$userRatingsTotal = $data['result']['user_ratings_total'] ?? null;
return [
'rating' => $rating,
'user_ratings_total' => $userRatingsTotal,
];
} else {
// Handle error
return [
'error' => $data['status'],
];
}
}
// Example usage
$placeId = 'YOUR_PLACE_ID'; // Replace with your Google Place ID
$apiKey = 'YOUR_API_KEY'; // Replace with your API key
$placeDetails = getPlaceDetails($placeId, $apiKey);
if (isset($placeDetails['error'])) {
echo "Error: " . $placeDetails['error'];
} else {
echo "Rating: " . $placeDetails['rating'] . "n";
echo "Total Reviews: " . $placeDetails['user_ratings_total'] . "n";
}
?>
### Step 3: Replace Placeholder Values
Make sure to replace `YOUR_PLACE_ID` with the actual Place ID of the location you want to query and `YOUR_API_KEY` with your Google Places API key.
### Explanation of the Code
1. **getPlaceDetails()**: This function constructs the API URL, makes a GET request to the Google Places API, and retrieves the JSON response.
2. **Extracting Data**: The function checks the status of the response. If successful, it extracts the `rating` and `user_ratings_total` fields from the result.
3. **Error Handling**: If the API call fails, it returns the error status.
4. **Output**: The script prints the rating and total number of reviews for the specified place.
### Important Notes
– Ensure that you have enabled billing for your Google Cloud project, as the Places API may incur charges.
– Be mindful of the API usage limits to avoid unexpected costs.
– Check the [Google Places API documentation](https://developers.google.com/maps/documentation/places/web-service/details) for more details on response fields and options.
This should help you retrieve the total number of reviews and ratings for a Google Place using PHP!
### Step 1: Create a Custom Plugin
1. Create a new folder in the `wp-content/plugins/` directory, e.g., `google-place-reviews`.
2. Inside that folder, create a file named `google-place-reviews.php`.
### Step 2: Add Plugin Header and Code
Open the `google-place-reviews.php` file and add the following code:
<?php
/*
Plugin Name: Google Place Reviews
Description: Get total reviews and ratings from Google Places API.
Version: 1.0
Author: Your Name
*/
function get_place_details($place_id) {
$api_key = 'YOUR_API_KEY'; // Replace with your Google Places API key
// URL for Google Places API
$url = "https://maps.googleapis.com/maps/api/place/details/json?place_id={$place_id}&key={$api_key}";
// Make the API request
$response = wp_remote_get($url);
if (is_wp_error($response)) {
return [
'error' => $response->get_error_message(),
];
}
$data = json_decode(wp_remote_retrieve_body($response), true);
// Check if the request was successful
if ($data['status'] === 'OK') {
// Extract rating and user reviews count
$rating = $data['result']['rating'] ?? null;
$user_ratings_total = $data['result']['user_ratings_total'] ?? null;
return [
'rating' => $rating,
'user_ratings_total' => $user_ratings_total,
];
} else {
// Handle error
return [
'error' => $data['status'],
];
}
}
// Example usage: Add a shortcode to display the rating and total reviews
function display_place_reviews($atts) {
$atts = shortcode_atts(
array(
'place_id' => '',
),
$atts,
'place_reviews'
);
if (empty($atts['place_id'])) {
return 'Place ID is required.';
}
$place_details = get_place_details($atts['place_id']);
if (isset($place_details['error'])) {
return "Error: " . $place_details['error'];
} else {
return "Rating: " . esc_html($place_details['rating']) . "<br>Total Reviews: " . esc_html($place_details['user_ratings_total']);
}
}
// Register the shortcode
add_shortcode('place_reviews', 'display_place_reviews');
### Step 3: Replace Placeholder Values
Make sure to replace `YOUR_API_KEY` with your actual Google Places API key.
### Step 4: Activate the Plugin
1. Go to the WordPress admin dashboard.
2. Navigate to **Plugins** > **Installed Plugins**.
3. Find **Google Place Reviews** in the list and click **Activate**.
### Step 5: Use the Shortcode
Now, you can use the shortcode `[place_reviews place_id="YOUR_PLACE_ID"]` in your posts, pages, or widgets, replacing `YOUR_PLACE_ID` with the actual Place ID you want to query.
### Example Usage in WordPress
[place_reviews place_id="YOUR_PLACE_ID"]
### Notes
– This code uses `wp_remote_get()` to make the API request, which is the recommended way to perform HTTP requests in WordPress.
– The shortcode will output the rating and total number of reviews for the specified Google Place.
– Be sure to handle any potential errors in production, especially regarding the API key and Place ID validity.
This setup will load the WordPress environment and allow you to fetch and display Google Place reviews and ratings directly within your WordPress site.
### Option 1: Run on Every Page Load (Using `wp_loaded`)
Here’s how you can modify your custom plugin to make the Google Places API request every time WordPress loads:
1. **Modify Your Plugin Code:**
Update your `google-place-reviews.php` file as follows:
<?php
/*
Plugin Name: Google Place Reviews
Description: Get total reviews and ratings from Google Places API.
Version: 1.0
Author: Your Name
*/
function get_place_details($place_id) {
$api_key = 'YOUR_API_KEY'; // Replace with your Google Places API key
// URL for Google Places API
$url = "https://maps.googleapis.com/maps/api/place/details/json?place_id={$place_id}&key={$api_key}";
// Make the API request
$response = wp_remote_get($url);
if (is_wp_error($response)) {
return [
'error' => $response->get_error_message(),
];
}
$data = json_decode(wp_remote_retrieve_body($response), true);
// Check if the request was successful
if ($data['status'] === 'OK') {
// Extract rating and user reviews count
$rating = $data['result']['rating'] ?? null;
$user_ratings_total = $data['result']['user_ratings_total'] ?? null;
return [
'rating' => $rating,
'user_ratings_total' => $user_ratings_total,
];
} else {
// Handle error
return [
'error' => $data['status'],
];
}
}
// Function to run on every page load
function fetch_place_reviews() {
$place_id = 'YOUR_PLACE_ID'; // Replace with your Google Place ID
$place_details = get_place_details($place_id);
// You can store the results in a transient or an option
if (isset($place_details['error'])) {
error_log("Google Places API Error: " . $place_details['error']);
} else {
// Store results in a transient for a short time to avoid too many requests
set_transient('google_place_reviews', $place_details, HOUR_IN_SECONDS);
}
}
// Hook into wp_loaded to fetch reviews
add_action('wp_loaded', 'fetch_place_reviews');
// Shortcode to display the cached results
function display_place_reviews() {
$place_details = get_transient('google_place_reviews');
if (!$place_details) {
return 'No reviews available or failed to fetch.';
}
return "Rating: " . esc_html($place_details['rating']) . "<br>Total Reviews: " . esc_html($place_details['user_ratings_total']);
}
// Register the shortcode
add_shortcode('place_reviews', 'display_place_reviews');
### Explanation of Changes
1. **Fetch Place Reviews**: The `fetch_place_reviews` function is defined to make the Google Places API call. It runs every time the WordPress site loads.
2. **Transient Storage**: Instead of fetching the data on every page load, which can be inefficient and lead to rate limits, the response is cached in a WordPress transient using `set_transient()`. This allows you to retrieve the data for a specified duration (in this case, one hour).
3. **Display Shortcode**: The `display_place_reviews` function retrieves the cached data and outputs it.
### Important Considerations
– **Rate Limiting**: Be cautious about how often you call the Google Places API to avoid hitting quota limits or incurring excessive charges. The transient system helps mitigate this by caching the results.
– **Debugging**: Use `error_log()` to log any errors to help with debugging in your development environment.
– **Replacing Place ID**: Ensure you replace `YOUR_PLACE_ID` and `YOUR_API_KEY` with the actual values.
### Using the Shortcode
You can use the shortcode `[place_reviews]` in your posts, pages, or widgets to display the cached rating and total reviews whenever the page loads.
This setup allows you to fetch and store Google Place reviews efficiently, ensuring that you are not making excessive API calls while still providing fresh data to users.