Advanced Custom Fields (ACF) is a plugin for WordPress that allows you to add custom fields to your WordPress content. You can use ACF to store Google Maps locations and then display them on your WordPress site using a custom function.

Here is an example of a custom function that you can use to display a Google Map on your WordPress site using ACF:

function display_map() {

            // Check if ACF is installed and active.

            if ( !function_exists( 'get_field' ) ) {

                        return;

            }

            // Get the map location field value.

            $location = get_field( 'map_location' );

            // Check if a location has been set.

            if ( ! $location ) {

                        return;

            }

            // Enqueue the Google Maps JavaScript API.

            wp_enqueue_script( 'google-maps', 'https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY', array(), '', true );

            // Set up the map options.

            $map_options = array(

                        'zoom' => 14,

                        'center' =>array(

                                    'lat' => $location['lat'],

                                    'lng' => $location['lng'],

                        ),

            );

            $map_options = json_encode( $map_options );

            // Output the map container and JavaScript.

            echo '<div id="map" style="height: 400px;"></div>';

            echo '<script>';

            echo 'var map;';

            echo 'function initMap() {';

            echo 'map = new google.maps.Map(document.getElementById("map"), ' . $map_options . ');';

            echo 'var marker = new google.maps.Marker({';

            echo 'position: {lat: ' . $location['lat'] . ', lng: ' . $location['lng'] . '},';

            echo 'map: map';

            echo '});';

            echo '}';

            echo '</script>';

}

You can then call this function wherever you want to display the map on your site. Be sure to replace “YOUR_API_KEY” with your own Google Maps API key.

For more information on using ACF in WordPress, you can refer to the ACF documentation: https://www.advancedcustomfields.com/resources/

Categorized in: