Google Places API With ACF [closed]

Anything to do with using the Google Places API is going to be off-topic here, but the best place to start would be the developer docs.

However, how you interact with the API data within WordPress is certainly on-topic. I would suggest a wrapper function that caches the results periodically:

/**
 * Get places data for a post.
 * 
 * @param   int|WP_Post $post   Optional, defaults to current post.
 * @return  mixed
 */
function wpse_187541_google_places_data( $post = null ) {
    if ( ! $post = get_post( $post ) )
        return;
    if ( ! $place_id = get_post_meta( $post->ID, 'place_id', true ) )
        return; // No place ID configured for this post

    if ( $data = get_post_meta( $post->ID, 'place_data', true ) ) {
        if ( $data->timeout <= current_time( 'timestamp' ) )
            $data = null; // Void the cache if it's old
    }

    if ( ! $data ) {
        $args = http_build_query(
            array(
                'key' => '', // API key
                'placeid' => $place_id,
            )
        );

        $http = wp_remote_get( "https://maps.googleapis.com/maps/api/place/details/json?$args" );
        if ( $body = wp_remote_retrieve_body( $http ) ) {
            if ( $data =@ json_decode( $body ) )
                $data->timeout = current_time( 'timestamp' ) + HOUR_IN_SECONDS; // Cache data for 1 hour
        }

        if ( $data ) {
            update_post_meta( $post->ID, 'place_data', $data );

        } else {
            // Something went wrong.
            // Perhaps check HTTP response and decide cause of problem.
            // Don't want to keep hitting the API on every call if the error is permanent (i.e. invalid place id etc.)
        }

    }

    return $data;
}

Leave a Comment