Skip to content

Instantly share code, notes, and snippets.

@mustardBees
Last active August 24, 2022 11:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mustardBees/aef85b72411cb83d20261cd632306ab4 to your computer and use it in GitHub Desktop.
Save mustardBees/aef85b72411cb83d20261cd632306ab4 to your computer and use it in GitHub Desktop.
Here is a WordPress function to get Google reviews by place ID, which you can use as is or modify for your own website needs.
<?php
/**
* Get Google reviews by place ID.
*
* @param $google_place_id Google place ID.
*
* @return void
*/
function kanuka_get_google_reviews( $google_place_id ) {
// Bail if we don't have a Google place ID.
if ( empty( $google_place_id ) ) {
return;
}
// Call Google Places API.
$request = wp_remote_get( add_query_arg( array(
'place_id' => $google_place_id,
'key' => 'YOUR_API_KEY',
), 'https://maps.googleapis.com/maps/api/place/details/json' ) );
// The body of the response.
$body = wp_remote_retrieve_body( $request );
// Bail if there's a problem.
if ( empty( $body ) ) {
return;
}
// Decode JSON into PHP array.
$array = json_decode( $body );
// Check we have a valid response.
if ( empty( $array ) || ! isset( $array->result->reviews[0] ) ) {
return;
}
return $array->result->reviews;
}
?>
<?php $reviews = kanuka_get_google_reviews( 'ChIJRWNGE00EdkgRwyaONRrJ4A8' ); ?>
<?php if ( ! empty( $reviews ) ) : ?>
<ul class="reviews">
<?php foreach ( $reviews as $review ) : ?>
<?php
// Only show 4 or 5 star reviews.
if ( ! in_array( $review->rating, array( 4, 5 ) ) ) {
continue;
}
?>
<li class="reviews__item">
<h1><?php echo $review->author_name; ?></h1>
<p><?php echo $review->rating; ?> / 5</p>
<p><?php echo $review->relative_time_description; ?></p>
<?php echo wpautop( $review->text ); ?>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment