0

I'm creating a site that has a Venue custom post type, and one of the custom fields (using advanced custom fields) is the hours of operation for the business. I was going to manually find this information and plug it in myself, but that's a lot of work, and it changes seasonally, which Vermont has a lot of. That being said, I feel my best solution is to use the Google Places API.

I have absolutely no idea how to use this at this time, but I'd love to learn. I'll be researching this in my free time, but if anyone could lend me a helping hand, that would be greatly appreciated.

Does anyone know if / how complicated it would be to grab the hours of operation from the Google Places API? If I was to store the "place ID" (I think that's what Google is using now) in an ACF field, could I dynamically read the hours through a template? Just tossing out ideas, but if anyone could help me with this, that would be greatly appreciated!

1

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;
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.