Google Maps in Generateblocks' loop

25 views Asked by At

I would like to get all the maps in a Generateblocks loop with their title, featured image and the google maps shortcode. I want to display all entries with their maps as an archive. The variable "gmap" is not a Google maps ACF field because for this to work you need the API and this is not the purpose. The variable "gmap" is taken from an ACF text field, this field supports both addresses and coordinates with the shortcode.

I leave here below the code I used, this works to insert a map in a post, page or CPT, but it doesn't work inside Generateblocks loops or Wordpress loops to get map listings:

add_shortcode('google_map', 'display_google_map');

function display_google_map($atts) {
    // Sets defaults and overwrites with the attributes provided.
    $atts = shortcode_atts(
        array(
            'address_field' => 'gmap', // The name of the ACF custom field that contains the address
            'width' => '100%', // Map width
            'height' => '400px', // Map height 
            'zoom' => 15 // Default zoom level 
        ),
        $atts
    );

    // Checks if an ACF custom field name was provided
    if (empty($atts['address_field'])) {
        return 'Please specify the name of the ACF custom field containing the address.';
    }

    // Check if ACF is active
    if (!function_exists('get_field')) {
        return 'The Advanced Custom Fields (ACF) plugin is not activated.';
    }

    // Gets the address of the custom field ACF
    $address = get_field($atts['address_field']);

    // Check if the address is available
    if (empty($address)) {
        return 'No address found.';
    }

    // Generate the HTML code to display the map
    $map_html = '<div style="width: ' . esc_attr($atts['width']) . '; height: ' . esc_attr($atts['height']) . ';">';
    $map_html .= '<iframe width="' . esc_attr($atts['width']) . '" height="' . esc_attr($atts['height']) . '" frameborder="0" style="border:0" ';
    $map_html .= 'src="https://maps.google.com/maps?q=' . urlencode($address) . '&output=embed&z=' . esc_attr($atts['zoom']) . '"></iframe>';
    $map_html .= '</div>';

    return $map_html;
}

Thank you very much and best regards to the community.

0

There are 0 answers