Shortcode to show map markers of child pages with Advanced Custom Fields Pro

This post shows you how to create a shortcode that will display a map with markers of all the child pages of the current page. There is also a shortcode attribute to choose the parent page ID for the map, if you want to show the map elsewhere.

Create our Google Map field

First, lets create our map field.

Make sure you set the metabox ‘Location’ accordingly. I chose to only show the field if the parent page is ‘Data Centers’.

Next, you need to make sure you have child pages of that page. I created a page for each data center location my client had.

Set the location of child pages

On each of those child pages, set a location via the ACF Google Map field.

Custom javascript for our map

Now, the fun part… code.

Create a javascript file for the first part of our map code. Mine is called map.js, and I put it in:

Create our Google Map shortcode

It defaults to showing child pages of the page the shortcode is used on, but we can also put the shortcode anywhere, and specify the parent page we want to use.

[child_pages_map parent=”123″]

Naturally, change the parent ID to the one you want.

That’s it! You can easily tweak this code to grab locations of posts or a CPT, or a specific term in a taxonomy. It’s a great starting point to getting your google map how you want it, and where you want it.

Our posts, directly to your inbox

Comments

You might also be able to do without the ‘init’ hook and simply call wp_enqueue_script() to register and enqueue the files in one call:wp_enqueue_script( 'google-map', 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false', array(), '3', true );
wp_enqueue_script( 'amc-map', get_stylesheet_directory_uri() . '/js/map.js', array('google-map'), '1.0.0', true );

Hey Damien, wow thanks for pointing out that wp_print_script has been deprecated. I didn’t realize. I can’t register/enqueue the files all at once, otherwise they would load on every page. I updated the post and the code with Mike Jolley’s more current method of registering and enqueueing separately. This way, my scripts only load when the shortcode is used… much better now. Thanks!